Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在Meteor事件处理程序中访问模板帮助器字典_Javascript_Meteor_Meteor Blaze - Fatal编程技术网

Javascript 在Meteor事件处理程序中访问模板帮助器字典

Javascript 在Meteor事件处理程序中访问模板帮助器字典,javascript,meteor,meteor-blaze,Javascript,Meteor,Meteor Blaze,在Meteor中,我将两个对象从数据库发送到模板: Template.myTemplate.helpers({ helper1: function() { var object1 = this; // data context set in iron:router...path is context dependent // modify some values in object1 return this; }, helper2: function() {

在Meteor中,我将两个对象从数据库发送到模板:

Template.myTemplate.helpers({
  helper1: function() {
    var object1 = this;  // data context set in iron:router...path is context dependent
    // modify some values in object1
    return this;
  },
  helper2: function() {
    return Collection2.find({_id: this.object2_id});
  }
});
此模板还有一个事件处理程序,用于修改上面的两个对象。我试图从上面访问helper1和helper2,但如果调用模板的数据上下文,则只能访问未修改版本的object1。如何访问上面定义的帮助程序

Template.myTemplate.events({
  'submit form': function(event) {
    event.preventDefault();
    // Access helper2 object and attributes here instead of calling Collection2.find() again
  }
});

Helpers只是函数,因此可以随意传递并分配给其他变量,因此您可以定义一个函数,然后将模板Helpers的helper2键分配给它,并通过事件处理程序的原始引用进行调用

var helperFunction = function() {
    return Collection2.find({_id: this.object2_id});
};

Template.myTemplate.helpers({
    helper1: function() {
        var object1 = this;  // data context set in iron:router...path is context dependent
        // modify some values in object1
        return this;
    },
    helper2: helperFunction
});

Template.myTemplate.events({
    'submit form': function(event) {
        event.preventDefault();
        var cursor = helperFunction();
    }
});

如果您可以修改事件的帮助程序,那么Meteor应用程序的任何部分都可以,这与Blaze的设计理念背道而驰

Blaze被设计成一个具有诱惑力的单向数据绑定系统。您所要求的可以使用Angular(单独使用,或者与Blaze并排使用,请看)来实现,这本质上是一个具有诱惑力的双向数据绑定系统


您可能还想检查React,它也是一个双向数据绑定

无法使用当前的公共API调用帮助程序。Peppe,您可能知道这一点,但我刚刚发现有一个用于访问帮助程序的内部API-Template.myTemplate.\uhelpers.get('helper');鉴于这是内部的,我假设api将来可能会更改,因此在代码中经常使用它可能不是最好的主意。请记住,您不能依赖于在以这种方式调用的帮助程序中使用
this
,我猜
Template.instance()
也不会工作,除非您再违反一些公共api。@bgmaster,
Template.myTemplate.\uu helpers.get('helper')
太黑了,将来随时都可能过时。Blaze不是设计用来这样使用的。。。请在下面核对我的答案。这种模式有助于避免重复代码,这正是我的目标。我唯一要注意的是函数中的这一点可以更改。在事件处理程序中调用函数时,它将成为窗口对象,而不是数据上下文。考虑到事件处理程序仍然是数据上下文,我觉得这很奇怪。如果您可以更新您的答案以反映这一点,我会将其标记为正确。正如@bgmaster所指出的,您需要调用并提供
thisArg
,而不是简单地调用函数。但是,在这种情况下,您不知道
thisArg
应该是什么(并且使用
{{helper2}}
的时间可能不同,因此这通常不起作用)。