Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js: Collapsing/deferring expensive observers or computed properties

Tags:

ember.js

In an Ember app, say you have an observer or a property that watches an array, like so:

topContributor: (function() {
  // ... loop over articles (hence slow) ...
}).property('[email protected]')

Updating the articles array, through ember-data for instance, repeatedly triggers the property function for a total of articles.length times.

Is there a way to collapse the updates into one lazy update when all the changes have finished and the runloop is flushed?

like image 645
Jo Liss Avatar asked Sep 17 '12 21:09

Jo Liss


1 Answers

Thanks to @wagenet and @krisselden for the following pointers:

At the moment, while bindings are deferred (lazy), observers and by extension computed properties trigger immediately. In the future, they might become deferred as well.

In the meantime, you can use Ember.run.once as a workaround to schedule a deferred function call, which will be run only once. Computed properties, I suppose, can be easily turned into observers to follow the same pattern. Here is an example:

updateTopContributor: function() {
  // ... loop over articles (hence slow) ...
  this.set('topContributor', ...);
},

_updateTopContributorObserver: (function() {
  Ember.run.once(this, 'updateTopContributor');
}).observes('[email protected]')
like image 98
Jo Liss Avatar answered Nov 01 '22 04:11

Jo Liss