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

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.

主站蜘蛛池模板: 长海县| 柞水县| 平谷区| 铜山县| 平山县| 彩票| 乃东县| 大姚县| 长白| 米易县| 资阳市| 灯塔市| 柳江县| 谷城县| 平顺县| 潞西市| 东平县| 阜新| 鹰潭市| 二连浩特市| 宝山区| 南和县| 增城市| 蒲江县| 梅州市| 简阳市| 和硕县| 湘阴县| 文成县| 临潭县| 萍乡市| 仪陇县| 云南省| 新竹市| 天水市| 安化县| 东莞市| 辽阳县| 镇平县| 上栗县| 普宁市|