Meteor, call function in child template from parent template
Based on my experience with Meteor, it seems like it favors more of an event driven UI design. This means that you would not directly call the parent or child methods directly, but you would fire a custom event or set a Session variable. So you could do something like:
Template.Container.helpers( {
callBack: function () {
Session.get('button.lastClickTime');
console.log( 'this is my callback' );
}
} );
Template.Content.events( {
'click button': function ( e, tmpl ) {
Session.set('buttom.lastClickTime', new Date());
}
} );
The Session object is reactive so the callback method will be called anytime that 'button.lastClickTime' Session value is set.
Then you could just reverse the set/get calls to notify the child from the parent.
You can register an event handler on the parent template that triggers on events in the child template by using a Selector that matches elements in the child template, like this:
Template.Container.events( { // 'Container' is the parent template
'click button': function ( e, tmpl ) { // Selector for an element in the child-template*
// You will now have access to the parent's context instead of the child's here.
}
} );
*) Assuming there are no other buttons in the parent template. If so, make a unique name to the button so you can uniquely select it from the parent.
Here's a pattern you could use. Define a class Child
and a template child
; the idea is that inside the child
template, the data context is a Child
instance. For example, I'll create a component which has a number that can be incremented by pressing a button.
<template name="child">
<button class="increment">{{number.get}}</button>
</template>
function Child() {
this.number = new ReactiveVar(0);
}
Template.child.events({
"click .increment": function () {
this.number.set(this.number.get() + 1);
}
});
In the parent's created
callback, create a Child
instance and store it on the template instance. Then in the parent template, call out to child
, passing in the Child
as a data context:
Template.parent.created = function () {
this.childInstance = new Child();
}
Template.parent.helpers({
childInstance: function () {
return Template.instance().childInstance;
}
});
<template name="parent">
{{> child childInstance}}
</template>
Now you can define methods on the Child
prototype and call them from the parent template, for example:
Child.prototype.getNumberTimesTwo = function () {
return this.number.get() * 2;
}
<template name="parent">
{{> child childInstance}}
That number multiplied by two is: {{childInstance.getNumberTimesTwo}}
</template>