【问题标题】:How can I listen to one event from two template handlers?如何监听来自两个模板处理程序的一个事件?
【发布时间】:2015-03-30 15:43:17
【问题描述】:

例如,在下面,只有foo 事件处理程序被调用。 (这很奇怪——我原以为会调用 bar 事件处理程序,因为 <form> 元素在 bar 模板中。)

<template name="foo">
  {{#bar klass="down"}}
    <button type="submit">test</button>
  {{/bar}}
</template>

<template name="bar">
  <form>
    {{> Template.contentBlock}}
  </form>
</template>

Template.foo.events 
  'submit form' ->
    alert 'foo'

Template.bar.events 
  'submit form' ->
    alert 'bar'

【问题讨论】:

  • meteorpad 中,将coffeescript 转换为js(coffeescript 包在meteorpad 中不起作用),您的代码可以触发两个事件。也许我犯了一个幸运的错字,但我认为您的问题可能出在其他地方。
  • 我的代码库中有错字,谢谢你的重现。两者都被调用,bar 事件优先。

标签: meteor spacebars


【解决方案1】:

看看this 包,你只声明了1个事件处理程序,你可以在任何你想要的模板上使用。

来自文档的示例。

   //here we declare 1 only event
    Template.foo.events({
      'click button': function (event, template) {
        console.log("foo button clicked");
      }
    }); 

//here we inherit 
Template.foo2.inheritsEventsFrom("foo"); //where foo2 is another Template, and now have access to the event from foo template

祝你好运

【讨论】:

  • 谢谢,我知道如何使用这个包为两个模板调用相同的事件处理程序。但是,我想要调用两个单独的函数。 bar 中的那个总是相同的,但是包含bar 的模板中的处理程序会有所不同。
【解决方案2】:

如何做到这一点的答案是问题中的代码,实际上它可以按预期工作。调用bar 处理程序,然后调用foo 处理程序。

http://meteorpad.com/pad/kLwjq8N7T5fb2qwjA/event%20bubbling

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-25
    相关资源
    最近更新 更多