0

父 Meteor 模板是否可以直接访问子模板?理想情况下,我想使用模板和带有 API 的小部件。我希望有这样的事情:

我的页面.html

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

我的页面.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();
    }
});

我的小部件.html

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

mywidget.js

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

以上不起作用,因为myWidgetInstance.getMyValue()不存在。外部代码似乎没有办法访问实例上的模板辅助函数。

是否有人以我在上面尝试使用 Meteor 模板的方式使用它们?或者这是否更适合单独的 jQuery 小部件?如果是这样,那就太可惜了,因为我仍然希望我的小部件模板能够从 Meteor 提供的功能中受益。

4

1 回答 1

1

可以访问子模板辅助功能。一旦您应用了一些修复程序,您的示例将起作用:

修复1:getValue() 而不是 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);
    }
});

修复 2:$('input').val(); 改为 this.$('input').val();

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

修复 3:<input>不应该有关闭标签。

<template name="myWidget">
   <input type="text" value="sample value">
</template>
于 2014-06-14T09:47:48.613 回答