EmberJS Set Multiple Properties At Once

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

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?

回答1:

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.



回答2:

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!



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!