当我通过集合方法add或push向集合添加新模型时,有没有办法不触发add事件 示例:
collection.add({name: 'any name'})
我尝试过给予
collection.add({name: 'xyz'}, {add: false})
但它不起作用
最佳答案
@idbehold 完美地回答了这个问题。您可以在选项中传递 {silent: true}
来抑制 add
事件。我只想添加文档中的一些信息。阅读其中内容
Generally speaking, when calling a function that emits an event (model.set, collection.add, and so on...), if you'd like to prevent the event from being triggered, you may pass {silent: true} as an option.
Note that this is rarely, perhaps even never, a good idea.
Passing through a specific flag in the options for your event callback to look at, and choose to ignore, will usually work out better.
因此,请考虑在选项中传递一个附加标志,并在事件监听器中检查该标志以忽略您不需要的内容。
检查这个Jsbin Example
var M = Backbone.Model.extend({ defaults: { a: 5 } });
var C = Backbone.Collection.extend({ model: M });
var c = new C();
var m = new M({a:1});
c.on('add', function(model, collection, options) {
console.log(options);
if (!options.flag) { return; }
});
c.add(m, {flag: false});
关于backbone.js - 将模型添加到集合时不触发添加事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23712412/