首先,我进行了一些搜索,但在 stackoverflow/google 上没有找到我想要的答案。
这是我的代码片段:
//in the view
this.collection.on("add",triggerthis)
this.collection.add(predefinedModel)
triggerthis: function(a, b, c, d){
//etc.
}
基本上,我希望能够在 add 上传递参数并在 triggerthis 中接收参数。这可能吗?
提前致谢。
最佳答案
如果不使用未记录的功能,您将无法按照自己的方式执行此操作。
如果我们看一下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
的文档化界面:
trigger
object.trigger(event, [*args])
Trigger callbacks for the given event, or space-delimited list of events. Subsequent arguments to trigger will be passed along to the event callbacks.
因此 add
会将监听器调用为 f(model, collection, options)
其中 options
与 options
你传递给 Collection#add
的内容。结果是,如果你这样做:
this.collection.add(predefinedModel, { undocumented: 'arguments' })
然后你可以在你的回调中这样做:
triggerthis: function(model, collection, options) {
console.log(options.undocumented);
}
演示:http://jsfiddle.net/ambiguous/bqWwQ/
您当然可以通过选项
这种方式隧道化整个数组或对象。
“add”
事件的第三个参数没有记录(至少我找不到),最接近记录的是 0.3.3 Changelog entry 中的注释。 :
The ubiquitous
options
argument is now passed as the final argument to all"change"
events.
我不推荐这种方法,但如果您需要它,它就在那里;你当然需要在你的测试套件中覆盖它,你需要确保你没有在 Backbone 将使用的 options
中使用任何键。
更安全的方法是为模型附加一些额外的属性:
model.baggage = { some: 'extra stuff };
然后在回调中剥离它:
triggerthis: function(model, collection) {
var baggage = model.baggage;
delete model.baggage;
//...
}
演示:http://jsfiddle.net/ambiguous/M3UaH/
您还可以针对不同的目的使用不同的回调,或者将您的额外参数作为完整的模型属性传递。
还有 _.bind
:
this.collection.on("add", _.bind(function(collection, model, extra) { ... }, context, collection, model, 'whatever you want'));
但这将从左到右绑定(bind)参数,因此您必须指定所有您的回调将需要的参数。
关于javascript - 将参数传递给主干中的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11174125/