官术网_书友最值得收藏!

Adding events

To make our template a bit more dynamic, we will add a simple event, which will reactively rerun the logContext helper we created earlier.

First, however, we need to add a button to our contextExample template:

<button>Get some random number</button>

To catch the click event, open examples.js and add the following event function:

Template.contextExample.events({
  'click button': function(e, template){
    Session.set('randomNumber', Math.random(0,99));
  }
});

This will set a session variable called randomNumber to a random number.

Note

We will talk in depth about sessions in the next chapter. For now, we only need to know that when a session variable changes, all functions that get that session variable using Session.get('myVariable') will run again.

To see this in action, we will add a Session.get() call to the logContext helper, and return the former set's random number as follows:

Template.contextExample.helpers({
  logContext: function(){
    console.log('Context Log Helper',this);

    return Session.get('randomNumber');
  }
});

If we go to the browser, we will see the Get some random number button. When we click on it, we see a random number appearing just above the button.

Note

When we use the contextTemplates template multiple times in our home template, we will see that each instance of that template helper will display the same random number. This is because the session object will rerun all its dependencies, all of which are instances of the logHelper helper.

Now that we have covered template helpers, let's create a custom block helper.

主站蜘蛛池模板: 突泉县| 化德县| 宣城市| 金山区| 巧家县| 龙江县| 合江县| 徐闻县| 大竹县| 日土县| 砚山县| 望谟县| 德昌县| 宜州市| 鄂托克前旗| 隆昌县| 济源市| 城口县| 修文县| 澎湖县| 淮南市| 固始县| 明光市| 洛浦县| 武定县| 黄梅县| 临桂县| 崇明县| 松阳县| 陆川县| 宿州市| 信阳市| 宁陕县| 桐柏县| 武夷山市| 信丰县| 绵竹市| 乌拉特前旗| 沭阳县| 霸州市| 罗甸县|