Brad Vogel
Brad Vogel

Reputation: 486

Meteor templates accessing subtemplate helper functions

Is it possible for a parent Meteor template to access a subtemplate directly? Ideally, I'd like to use templates a widgets with an API. I was hoping for something like this:

mypage.html

<template name="myPage">
   <div class="widgetContainer"></div>
   <button>submit</button>
</template>

mypage.js

Template.myPage.rendered = function(){
    this.myWidgetInstance = UI.render(Template.myWidget)
    UI.insert(this.myWidgetInstance, $('.widgetContainer')[0]);
}

Template.myPage.events({
    'click button': function(e, template){
         // I don't want this logic to live inside of mywidget.js.
         // I also don't want this template to know about the <input> field directly.
         var val = template.data.myWidgetInstance.getMyValue();
    }
});

mywidget.html

<template name="myWidget">
   <input></input>
</template>

mywidget.js

Template.myWidget.getValue = function(){
    return this.$('input').val();
}

The above doesn't work because myWidgetInstance.getMyValue() doesn't exist. There doesn't appear to be a way for external code to access template helper functions on an instance.

Is anyone using Meteor templates in the way I'm trying to use them above? Or is this better suited for a separate jQuery widget? If so, it'd be a shame because I still want my widget template to benefit from the features Meteor provides.

Upvotes: 0

Views: 531

Answers (1)

Kuba Wyrobek
Kuba Wyrobek

Reputation: 5273

It is possible to access subtemplate helper function. Your example will work once you apply few fixes:

fix 1 : getValue() instead of getMyValue()

Template.myPage.events({
    'click button': function(e, template){
         // I don't want this logic to live inside of mywidget.js.
         // I also don't want this template to know about the <input> field directly.
         var val = template.myWidgetInstance.getValue();
         console.log(val);
    }
});

fix 2 : $('input').val(); instead this.$('input').val();

Template.myWidget.getValue = function(){
    return $('input').val();
}

fix 3 : <input> should have no close tag.

<template name="myWidget">
   <input type="text" value="sample value">
</template>

Upvotes: 1

Related Questions