将参数传递给骨干中的事件

时间:2012-06-24 00:39:16

标签: javascript events backbone.js backbone-events

首先,我做了一些搜索,没有回复stackoverflow / google为我提供了我想要的东西。

以下是我的代码片段:

//in the view
this.collection.on("add",triggerthis)
this.collection.add(predefinedModel)
triggerthis: function(a, b, c, d){
    //etc.
}

基本上,我希望能够传递一个关于add的参数并在triggerthis中接收参数。这可能吗?

提前致谢。

2 个答案:

答案 0 :(得分:30)

如果不使用未记录的功能,则无法以您希望的方式执行此操作。

如果我们看一下Collection#add,我们会看到:

add: function(models, options) {
  //...
  for (i = 0, l = add.length; i < l; i++) {
    (model = add[i]).trigger('add', model, this, options);
  }
  //...
}

注意trigger的第四个参数。如果我们查看trigger的文档化界面:

  

触发 object.trigger(event, [*args])

     

触发给定事件或以空格分隔的事件列表的回调。 触发器的后续参数将传递给事件回调。

因此,add会将听众称为f(model, collection, options),其中options与您传递给options的{​​{1}}相同。结果是,如果你这样做:

Collection#add

然后你可以在你的回调中做到这一点:

this.collection.add(predefinedModel, { undocumented: 'arguments' })

演示:http://jsfiddle.net/ambiguous/bqWwQ/

你当然可以通过这种方式通过triggerthis: function(model, collection, options) { console.log(options.undocumented); } 隧道传输整个数组或对象。

options事件的第三个参数没有记录(至少不是我能找到的),最接近文档的是0.3.3 Changelog entry中的注释:

  

无处不在的"add"参数现在作为所有options事件的最终参数传递。

我不推荐这种方法,但如果你需要的话,它就在那里;您当然需要在测试套件中介绍这一点,并且您需要确保不使用Backbone将使用的"change"中的任何键。


更安全的方法是将一些额外的属性附加到模型中:

options

然后在回调中将其剥离:

model.baggage = { some: 'extra stuff };

演示:http://jsfiddle.net/ambiguous/M3UaH/

您也可以将不同的回调用于不同的目的,或将您的额外参数作为完整的模型属性传递。

还有_.bind

triggerthis: function(model, collection) {
    var baggage = model.baggage;
    delete model.baggage;
    //...
}

但是这将从左到右绑定参数,因此您必须指定 all 您的回调所需的参数。

演示:http://jsfiddle.net/ambiguous/jUpJz/

答案 1 :(得分:6)

如果传递给该函数的值始终相同,您可以_.bind使用Function.bind(或本机add如果可用)

E.g。将处理程序绑定到triggerThis的位置(假设this.collection.on('add', _.bind(this.triggerThis, this, a, b, c, d)); 是您视图中的方法):

triggerThis

triggerThis: function(a, b, c, d /*, model, collection, options - if you need them*/) { ... } 的定义:

options

如果要将参数传递给个人添加调用,可以使用第二个add参数this.collection.on('add', this.triggerThis, this); this.collection.add(model, { someCustomValue: 'hello'; }); ,然后在事件处理程序中处理它。

E.g。

triggerThis: function(model, collection, options) {
  var val = options.someCustomValue;
  ...
}

然后在你的处理程序中:

{{1}}
相关问题