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

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.

主站蜘蛛池模板: 建昌县| 望谟县| 博兴县| 眉山市| 西吉县| 宜城市| 遂宁市| 嘉禾县| 光泽县| 仁怀市| 洛南县| 吐鲁番市| 屯留县| 霸州市| 和顺县| 安康市| 阳山县| 庆云县| 台州市| 东平县| 扎兰屯市| 苏尼特左旗| 龙海市| 科技| 青铜峡市| 泉州市| 通道| 宁波市| 灵武市| 宝清县| 安龙县| 唐山市| 沂源县| 三原县| 双城市| 龙门县| 上杭县| 临邑县| 封开县| 晋中市| 辽源市|