【问题标题】:How to pass meteor template helper as a parameter to meteor event handler?如何将流星模板助手作为参数传递给流星事件处理程序?
【发布时间】:2015-07-18 07:57:16
【问题描述】:

这是我的问题:

在模板文件中:

<template name="button">
     <button class="btn-class">{{disp}}</button>
</template>

在js中:

Template.button.events({
    'click': function(event, templ) {
         if (this.onClick) {
             this.onClick();
         }
    }
})

在其他使用“按钮”的模板中:

<template name="buttonGroup">
     {{> button disp='button 1' onClick=onButton1Click}}
     {{> button disp='button 2' onClick=onButton2Click}}
</template>

及其js:

Template.buttonGroup.helpers({
    onButton1Click: function() {
        console.log('button 1 is clicked');
    },
    onButton2Click: function() {
        console.log('button 1 is clicked');
    },
});

显然,它不能工作,因为模板 buttonGroup 会将 'onButton1Click()' 传递给按钮,而不是函数而是结果(返回 'undefined')。

那么我该怎么做才能让流星将辅助函数作为参数传递给子模板?

【问题讨论】:

    标签: meteor


    【解决方案1】:

    在您的帮助程序中返回函数,而不是直接放入您要执行的代码:

    Template.buttonGroup.helpers({
      onButton1Click: function() {
        return function(event, template){
          console.log('button 1 is clicked');
        };
      },
      onButton2Click: function() {
        return function(event, template){
          console.log('button 1 is clicked');
        };
      }
    });
    
    Template.button.events({
      "click": function(event, template) {
        if (this.onClick) {
          this.onClick(event, template);
        }
      }
    });
    

    【讨论】:

      【解决方案2】:

      是否可以选择使用全局函数字典?

      JS:

      var fns = {
          onButton1Click: function(self) {
               // use self instead of this here
              console.log('button 1 is clicked');
          },
          onButton2Click: function(self) {
              console.log('button 1 is clicked');
          }
      }
      
      Template.button.events({
          'click': function(event, templ) {
               if (this.onClick) {
                   fns[this.onClick](this);
               }
          }
      })
      

      HTML 保持不变。

      【讨论】:

        猜你喜欢
        • 2015-06-07
        • 2015-07-24
        • 2016-11-17
        • 2013-05-22
        • 2014-08-22
        • 2015-06-09
        • 2015-04-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多