Batch Events
can.Observe.batchEvents
can.Observe.startBatch( batchStopHandler ) and
can.Observe.stopBatch( force, callStart )
are used to specify atomic operations. startBatch
prevents change events from being fired until stopBatch is called.
The following listens to changes on a
player:The "change" callback handler does not get called until after
tvshowis removed,songis added, andstopBatchis called.Performance and correctness are the two most common reasons to use batch operations.
Correctness
Sometimes, an object can be temporarily in an invalid state. For example, the previous
playershould have atvshoworsongproperty, but not both. Event listeners should never be called in an intermediate state. We can make this happen withstartBatch,stopBatchand thecan/observe/setterplugin as follows:Use
startBatchandstopBatchto make sure events are triggered when an observe is in a valid state.Performance
CanJS synchronously sends events when a property changes. This makes certain patterns easier. For example, if you are doing live-binding, and change a property, the DOM is immediately updated.
Occasionally, you may find yourself changing many properties at once. To prevent live-binding from performing unnecessary updates, write the property updates within a
startBatch/stopBatch.Consider a list of items like:
And a template that renders the number of selected items:
The following updates the DOM once per click:
batchNum
All events created within a
startBatch/stopBatchshare the same batchNum value. To respond only once for a given batchNum, you can do it like:Automatic Batching
Libraries like Angular and Ember always batch operations. Set this up with:
This batches everything that happens within the same thread of execution and/or within 10 ms of each other.