将命名函数传递给事件映射 [英] Pass named function to an events map

查看:39
本文介绍了将命名函数传递给事件映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Meteor template that includes the following:

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

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

In my code (Coffeescript), I want to call a function by name from my event map (Backbone-style):

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 是不同的.我可以让它工作:

However, this fails. When I click on my button in the recipe template, I get Uncaught TypeError: Object editRecipe has no method 'call' (liveui.js:651) I learned event maps from Backbone, and maybe Meteor is different. I can get it to work with:

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

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

Is this the right way to do this? Or am I making some simple error? I've always liked using event maps this way because it summarizes the behaviors of the rendered template in just a few lines. Anonymous functions can spread the list out, making it harder to read, and of course they are not reusable.

推荐答案

您正在做的事情(稍后,事件定义指向一个函数)是正确的.将值作为函数名称(字符串)的事件映射是特定于主干的模式.流星不支持它.

What you are doing (later one, where event definition points to a function) is right. Event map with value as function name (string) is pattern specific to backbone. Meteor doesn't support it.

我一直喜欢以这种方式使用事件映射,因为它总结了仅用几行代码就可以了解渲染模板的行为.

I've always liked using event maps this way because it summarizes the behaviors of the rendered template in just a few lines.

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

But you can acheive similar functionality by doing something like this:

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

Personally, I don't like event-maps. cause its a mapping, which developer has to maintain manually. Working code @ https://gist.github.com/3010818

这篇关于将命名函数传递给事件映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆