2015-05-01 16 views
1

在Meteor中分享事件处理程序的最佳方式是什么?在Meteor.JS中分享活动的最佳方式

是否有一个大模板包裹在模板上?或者是通过创建一个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有事件和模板只需拨打电话

这两种方法哪一种最好?有没有比这更好的方法?

+0

尝试使用Template.registerHelper函数来定义全局模板助手。 http://docs.meteor.com/#/full/template_registerhelper –

回答

0

我在我的应用程序中使用了3种不同的模式。

  1. 您的第一个问题:在外部模板上定义事件处理程序,例如在我的默认布局模板中。这特别适合于经常重复使用的键盘事件。
  2. 第二个:定义有对象,我需要一个小型模板,事件和重用无处不在(例如,一个按钮)
  3. 使用dynamic templates并定义在容器模板事件。这实质上是第一种模式的更灵活的版本。
0

我说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'); 
    } 
}); 
相关问题