2014-12-06 70 views
0

在流星中有条件添加一组事件处理程序的最佳方式是什么?流星 - 有条件地返回一组事件处理程序

比如我试图做类似下面这段代码(此代码不能正常工作,但你会得到我想要实现这个想法。)

Template.page_article.events(function(){ 
    if (something){ 
    return { 
     some_event_name1, 
     some_event_name2, 
    } 
    } else { 
    return { 
     some_event_name3, 
     some_event_name4, 
    } 
    } 
}) 

什么最好的方法来做到这一点?我试图在events()之外设置一个变量,但我不喜欢那个解决方案,因为变量在所有其他模板之间共享。

回答

0

什么你想达到像一个不好解决的声音给我,但这里有一个办法做到这一点:

Template.page_article.events((function(){ 
    if (something){ 
    return { 
     '<event>': function(){ console.log("A1") }, 
     '<event>': function(){ console.log("A2") } 
    } 
    } else { 
    return { 
     '<event>': function(){ console.log("B1") }, 
     '<event>': function(){ console.log("B2") } 
    } 
    } 
})()) 

编辑

并与您添加的注释,它肯定听起来像一个不好的解决方案做这样的事情,而不是:

Template.page_article.events({ 
    '<event>': function(event, template){ 
     if(something){ 
      console.log("Do something A1") 
     }else{ 
      console.log("Do something B1") 
     } 
    } 
    '<event>': function(event, template){ 
     if(something){ 
      console.log("Do something A2") 
     }else{ 
      console.log("Do something B2") 
     } 
    } 
}) 
+0

谢谢,但你能帮我得到模板数据的变量SOMETHING吗?我试过Template.currentData()但没有用。我试图检查“edit_mode”变量是true还是false。如果为true,则返回所有允许编辑的事件,否则将不返回事件。 – Mcope 2014-12-06 11:11:52

+0

@Mcope,看我更新的答案。 – 2014-12-06 12:44:49

+0

那么,你的第二个编辑解决方案就是我一直在做的事情。除了有20个事件,如果某些事情是错误的,我根本不想运行。对我来说更有意义的是,如果可能的话,不要全部运行,而应该检查20次。但我想现在这将不得不做。 – Mcope 2014-12-06 19:26:05