分享Meteor.JS中的事件的最佳方法

问题描述 投票:1回答:2

在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具有事件和模板,只需从它们中调用

这两种方法中哪一种是最佳方法? 还有没有比这更好的方法了?

meteor meteor-blaze
2个回答
0
投票

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

  1. 您的第一个:在外部模板上定义事件处理程序,例如在我的默认布局模板中。 这特别适合于经常重复使用的事件,例如键盘事件。
  2. 第二个:定义一个小的模板,该模板包含我需要的对象和事件,并在各处重复使用(例如,一个按钮)
  3. 使用动态模板并在容器模板上定义事件。 从本质上讲,这是第一种模式的更灵活的版本。

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');
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.