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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:56:23  来源:igfitidea点击:

Backbone.js sync event in collection

javascriptjavascript-eventsbackbone.js

提问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 事件。您有几个选择:

  1. Just listen to the addevent and expect it be called repeatedly
  2. Emulate a single event by using a handler that has been debounced using the _.debounce()function.
  3. 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
    });
    
  1. 只听add事件并期望它被重复调用
  2. 使用已使用_.debounce()函数去抖动的处理程序来模拟单个事件。
  3. 来自fetch()jQuery XMLHttpRequest 对象的返回值。它实现了jQuery Deferred接口。所以你可以听那个结束。例如:

    myCollection.fetch({add:true}).done(function(){
        myView.render(); //or whatever
    });