EmberJS Set Multiple Properties At Once

后端 未结 2 1249
小鲜肉
小鲜肉 2021-02-05 02:06

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 wa

相关标签:
2条回答
  • 2021-02-05 02:12

    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!

    0 讨论(0)
  • 2021-02-05 02:20

    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.

    0 讨论(0)
提交回复
热议问题