Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  }
});
like image 649
bgmaster Avatar asked Sep 29 '22 00:09

bgmaster


1 Answers

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();
    }
});
like image 181
Kelly Copley Avatar answered Oct 01 '22 19:10

Kelly Copley