开发者

Batch Backbone.js events?

My app's framework is built around collapsing backbone models sending the data via websockets and updating models on other clients with the data. My question is how开发者_开发问答 should I batch these updates for times when an action triggers 5 changes in a row.

The syncing method is set up to update on any change but if I set 5 items at the same time I don't want it to fire 5 times in a row.

I was thinking I could do a setTimeout on any sync that gets cleared if something else tries to sync within a second of it. Does this seem like the best route or is there a better way to do this?

Thanks!


i haven't done this with backbone specifically, but i've done this kind of batching of commands in other distributed (client / server) apps in the past.

the gist of it is that you should start with a timeout and add a batch size for further optimization, if you see the need.

say you have a batch size of 10. what happens when you get 9 items stuffed into the batch and then the user just sits there and doesn't do anything else? the server would never get notified of the things the user wanted to do.

timeout generally works well to get small batches. but if you have an action that generates a large number of related commands you may want to batch all of the commands and send them all across as soon as they are ready instead of waiting for a timer. the time may fire in the middle of creating the commands and split things apart in a manner that causes problems, etc.

hope that helps.


Underscore.js, the utility library that Backbone.js uses, has several functions for throttling callbacks:

  • throttle makes a version of a function that will execute at most once every X milliseconds.
  • debounce makes a version of a function that will only execute if X milliseconds elapse since the last time it was called
  • after makes a version of a function that will execute only after it has been called X times.

So if you know there are 5 items that will be changed, you could register a callback like this:

// only call callback after 5 change events
collection.on("change", _.after(5, callback));

But more likely you don't, and you'll want to go with a timeout approach:

// only call callback 30 milliseconds after the last change event
collection.on("change", _.debounce(30, callback));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜