在流星事件处理程序中访问模板帮助器字典 [英] Accessing template helper dictionary in Meteor event handler

查看:68
本文介绍了在流星事件处理程序中访问模板帮助器字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Meteor, I'm sending two objects from my db to a template:

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的未修改版本.如何访问上面定义的助手?

This template also has an event handler to modify the two objects above. I am trying to access helper1 and helper2 from above, but if I call the data context of the template, I only get access to the unmodified version of object1. How do I access the helpers defined above?

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

推荐答案

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

Helpers are just functions and thus can be passed around and assigned to other variables at will, so you could define a function and then assign it the helper2 key of the template helpers and call by it's original reference from the event handler.

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();
    }
});

这篇关于在流星事件处理程序中访问模板帮助器字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆