【问题标题】:Pass named function to an events map将命名函数传递给事件映射
【发布时间】:2013-12-27 04:55:09
【问题描述】:

我有一个 Meteor 模板,其中包括以下内容:

{{#with selected_recipe}}
  {{>recipe}}
{{/with}}

在我的代码(Coffeescript)中,我想从我的事件映射(Backbone 样式)中按名称调用一个函数:

Template.recipe.events = {
  'click #btn-edit-recipe': 'editRecipe'
}

editRecipe = (event) ->
  console.log @  #should log the selected_recipe object
  #edit recipe

但是,这失败了。当我点击配方模板中的按钮时,我得到Uncaught TypeError: Object editRecipe has no method 'call' (liveui.js:651) 我从 Backbone 学习了事件映射,也许 Meteor 是不同的。我可以让它工作:

Template.recipe.events = {
  'click #btn-edit-recipe': -> editRecipe.call(@, event)
}

这是正确的方法吗?还是我犯了一些简单的错误?我一直喜欢以这种方式使用事件映射,因为它仅用几行就总结了渲染模板的行为。匿名函数可以将列表展开,使其更难阅读,当然它们也不能重用。

【问题讨论】:

    标签: meteor


    【解决方案1】:

    你在做什么(后来,事件定义指向一个函数)是正确的。 以值作为函数名称(字符串)的事件映射是特定于主干的模式。流星不支持它。

    我一直喜欢以这种方式使用事件地图,因为它总结了 渲染模板的行为只需几行。

    但是您可以通过执行以下操作来实现类似的功能:

    Template.recipe.doLogin = function(){};
    Template.recipe.requestData = function(){};
    
    //  OR Another way
    _.extend(Template.recipe, {
        "openFile":function(){},
        "editRecipe":function(){} 
    });
    
    //  now Events
    Template.recipe.events {
        'click #btn-edit-recipe': Template.recipe['editRecipe'],
        'click #btn-create-recipe': Template.recipe['createRecipe']
    }
    

    就我个人而言,我不喜欢事件映射。导致它的映射,开发人员必须手动维护。 编辑:工作代码@https://gist.github.com/3010818

    【讨论】:

    • 感谢纳奇克特的回复。我尝试了您的事件映射,但 Meteor 也不会这样做(Uncaught TypeError: Cannot call method 'call' of undefined (liveui.js:651) 尽管我可以从控制台成功调用Template.recipe['editRecipe']()。目前,我坚持从匿名中调用我的函数函数。你认为这是 Meteor 中的一个错误吗?
    • 感谢您花时间整理所有这些。我已经尝试过要点代码。它有效,并且运行它帮助我解决了我的问题。事实证明,我的 Template.recipe.events 对象是在我的 editRecipe 函数之前声明的。 Javascript 友好地崩溃并让您找到错误。使用 Coffeescript,由于某种原因,它可以编译并运行,但由于命名的函数在分配时未定义而失败。我猜我的-> editRecipe.call(@, event) 给了它函数范围,所以它会在调用时绑定。这让我对范围和提升进行了更深入的思考。谢谢!
    猜你喜欢
    • 2017-06-19
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 2021-12-03
    • 2020-01-05
    • 1970-01-01
    • 2012-02-19
    • 2019-05-01
    相关资源
    最近更新 更多