javascript 集合中的 Backbone.js 同步事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10756897/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Backbone.js sync event in collection
提问by Karol Sikora
According to doc here: http://documentcloud.github.com/backbone/#FAQ-eventscollection has sync event fired when i do something to sync collection with server. I try to invoke fetch method on collection and wait for sync event on it, but it never happens. Add event is fired, but I need only one event after syncing all items in collection to update corresponding view. There is another way to get this event fired?
根据此处的文档:http: //documentcloud.github.com/backbone/#FAQ-events集合已在我执行某些操作以将集合与服务器同步时触发了同步事件。我尝试在集合上调用 fetch 方法并等待它的同步事件,但它从未发生过。添加事件被触发,但在同步集合中的所有项目以更新相应的视图后,我只需要一个事件。还有另一种方法可以触发此事件吗?
回答by Karol Sikora
The solution is to fire up sync event maunually in 'success' callback passed as param to fetch method.
解决方案是在作为参数传递给 fetch 方法的“成功”回调中手动启动同步事件。
this.collection.fetch({add: true, success: function(collection, response){
collection.trigger('sync');
}});
回答by Brian Reischl
I believe the "sync" event is only fired when you change a model. So if you create, update or delete a model, then the "sync" event will fire.
我相信只有在更改模型时才会触发“同步”事件。因此,如果您创建、更新或删除模型,则会触发“同步”事件。
In your case, I think you want to listen for the "reset" event on the collection.
在您的情况下,我认为您想收听集合上的“重置”事件。
Edit:
If you're setting the {add:true}
option, then there is no single Backbone event that will fire after all the models have been added. You have a few options:
编辑:如果您正在设置该{add:true}
选项,则在添加所有模型后不会触发单个 Backbone 事件。您有几个选择:
- Just listen to the
add
event and expect it be called repeatedly - Emulate a single event by using a handler that has been debounced using the
_.debounce()
function. The return value from
fetch()
is a jQuery XMLHttpRequest object. It implements the jQuery Deferredinterface. So you could listen for that finish. For example:myCollection.fetch({add:true}).done(function(){ myView.render(); //or whatever });
- 只听
add
事件并期望它被重复调用 - 使用已使用
_.debounce()
函数去抖动的处理程序来模拟单个事件。 来自
fetch()
jQuery XMLHttpRequest 对象的返回值。它实现了jQuery Deferred接口。所以你可以听那个结束。例如:myCollection.fetch({add:true}).done(function(){ myView.render(); //or whatever });