che*_*lou 14 javascript events backbone.js backbone-events
首先,我做了一些搜索,没有回复stackoverflow /谷歌提供了我想要的东西.
这是我的代码片段:
//in the view
this.collection.on("add",triggerthis)
this.collection.add(predefinedModel)
triggerthis: function(a, b, c, d){
//etc.
}
Run Code Online (Sandbox Code Playgroud)
基本上,我希望能够传递一个关于add的参数并在triggerthis中接收参数.这可能吗?
提前致谢.
mu *_*ort 30
如果不使用未记录的功能,则无法以您希望的方式执行此操作.
如果我们看一下Collection#add,我们会看到:
add: function(models, options) {
//...
for (i = 0, l = add.length; i < l; i++) {
(model = add[i]).trigger('add', model, this, options);
}
//...
}
Run Code Online (Sandbox Code Playgroud)
注意第四个参数trigger.如果我们查看文档化的界面trigger:
触发
object.trigger(event, [*args])触发给定事件或空格分隔的事件列表的回调.触发器的后续参数将传递给事件回调.
因此,add将调用侦听器的f(model, collection, options)位置options与options传递给的内容相同Collection#add.结果是,如果你这样做:
this.collection.add(predefinedModel, { undocumented: 'arguments' })
Run Code Online (Sandbox Code Playgroud)
然后你可以在你的回调中做到这一点:
triggerthis: function(model, collection, options) {
console.log(options.undocumented);
}
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/ambiguous/bqWwQ/
你当然可以通过options这种方式隧道整个数组或对象.
"add"没有记录事件的第三个参数(至少不是我能找到的),最接近文档的是0.3.3 Changelog条目中的注释:
无处不在的
options论证现在作为所有"change"事件的最终论证传递.
我不推荐这种方法,但是如果你需要的话它就在那里; 您当然需要在测试套件中介绍这一点,并且您需要确保不使用optionsBackbone将使用的任何密钥.
更安全的方法是将一些额外的属性附加到模型:
model.baggage = { some: 'extra stuff };
Run Code Online (Sandbox Code Playgroud)
然后在回调中将其剥离:
triggerthis: function(model, collection) {
var baggage = model.baggage;
delete model.baggage;
//...
}
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/ambiguous/M3UaH/
您还可以将不同的回调用于不同的目的,或将您的额外参数作为完整的模型属性传递.
还有_.bind:
this.collection.on("add", _.bind(function(collection, model, extra) { ... }, context, collection, model, 'whatever you want'));
Run Code Online (Sandbox Code Playgroud)
但是这将从左到右绑定参数,因此您必须指定回调所需的所有参数.
演示:http://jsfiddle.net/ambiguous/jUpJz/
如果传递给函数的值始终相同,则可以使用(或本机如果可用)部分应用它_.bindFunction.bind
例如,您将处理程序绑定到的位置add(假设triggerThis是您视图中的方法):
this.collection.on('add', _.bind(this.triggerThis, this, a, b, c, d));
Run Code Online (Sandbox Code Playgroud)
定义triggerThis:
triggerThis: function(a, b, c, d /*, model, collection, options - if you need them*/) {
...
}
Run Code Online (Sandbox Code Playgroud)
如果要将参数传递给单个 add调用,可以使用第二个options参数add,然后在事件处理程序中处理该参数.
例如
this.collection.on('add', this.triggerThis, this);
this.collection.add(model, {
someCustomValue: 'hello';
});
Run Code Online (Sandbox Code Playgroud)
然后在你的处理程序:
triggerThis: function(model, collection, options) {
var val = options.someCustomValue;
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25325 次 |
| 最近记录: |