Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EmberJS Set Multiple Properties At Once

Tags:

ember.js

I am setting lots of properties with a series of set calls e.g.

this.set('prop1', value1); this.set('prop2', value2); ....... 

Is there a way to do this in one call (similar to when I create an object)? E.g.

this.setMultiple({prop1: value1, prop2: value2}); 

I still don't fully grok Ember's inheritance model. Maybe something along the lines of reopen?

like image 412
ghempton Avatar asked Jan 06 '12 02:01

ghempton


2 Answers

There is actually a function for this: setProperties. You can use it like this:

obj.setProperties({prop1: value1, prop2: value2}) 

obj should be instance of Ember.Object.

like image 92
oruen Avatar answered Oct 05 '22 23:10

oruen


As @oruen points out in his correct answer, you are describing setProperties(...).

One potential issue to be aware of is that according to the JS spec the order of properties on an object is indeterminate. (See Elements order in a "for (… in …)" loop).

If you don't care about order, or are confident that the JS implementations you are targeting will respect your order, setProperties should work for you.

When setting multiple properties, you should consider using Ember.beginPropertyChanges() and Ember.endPropertyChanges(). The former suspends the observer triggers and the latter restores it and flushes. This approach can improve performance. setProperties does this for you.

Also notable is Ember.changeProperties, which accepts a callback and calls Ember.beginPropertyChanges, then your callback, and then Ember.endPropertyChanges, even if your callback raised an exception. Example usage:

Ember.changeProperties(function() {   obj1.set('foo', mayBlowUpWhenSet);   obj2.set('bar', baz); }); 

Hope that helps!

like image 33
Luke Melia Avatar answered Oct 05 '22 23:10

Luke Melia