在Meteor中共享事件处理程序的最佳方法是什么?
是通过将一个大模板包裹起来吗? 还是通过创建JS类并从tehre中获取事件处理程序?
即选项1
<template name="wrap">
{{>tmpl1}}
</template>
<template name="wrap">
{{>tmpl2}}
</template>
然后将事件放入模板“包装”中
要么...
选项2
Template.tmpl1.events({
event1: function(e,t){ some_class.event1(e,t) }
})
Template.tmpl2.events({
event1: function(e,t){ some_class.event1(e,t) }
})
some_class具有事件和模板,只需从它们中调用
这两种方法中哪一种是最佳方法? 还有没有比这更好的方法了?
我在应用程序中使用了3种不同的模式。
我会说Dynamic Templates
:
<template name="wrap">
{{> Template.dynamic template=yourTemplate }}
</template>
然后,您可以创建一个Session
变量,以根据需要更改yourTemplate
,然后将显示正确的模板。 如果您使用的是iron-router
类的东西,则可以指定该模板以按路线更改:
Router.map(function () {
this.route('myEventTest', {
path: '/route-1',
template: 'wrap',
data: function () {
return {
yourTemplate: 'tmpl1' // the template you want changed
};
}
});
this.route('myEventTest', {
path: '/route-2',
template: 'wrap',
data: function () {
return {
yourTemplate: 'tmpl2'
};
}
});
});
然后为您的wrap
模板创建事件映射。
Template.wrap.events({
'click .element-in-either-template': function () {
console.log('okay');
}
});