简体   繁体   中英

Accessing template helper dictionary in Meteor event handler

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

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

If you can modify helpers from events, then, any part of the Meteor application can do, which is against the design philosophy of Blaze!

Blaze is designed to be uni-directional data binding tempting system. What you ask for can be achieved using Angular (used on its own, or side by side with Blaze, look at THIS ), which is by nature a 2-way data binding tempting system.

You may also want to check React, which is also a 2 way data binding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM