Observe properties on nested object

时间秒杀一切 提交于 2020-01-13 10:39:27

问题


Example fiddle: http://emberjs.jsbin.com/aviyUnA/9/edit?html,js,output

This is my model:

{
  name: {
    title: 'Mr',
    first: 'Potato',
    last:  'Head'
  },

  age: 79
}

How do I create a computed property that observes all the keys inside the name object without listing them manually?

fullName: function() {
  var name = this.get('name');
  return [name.title, name.first, name.last].join(' ');
}.property('name.??')

Thanks for any help!


回答1:


You can customize the set call of your model: Check if the value being set involves a property of name and if it does, call notifyPropertyChange on name:

App.MyModel = Ember.Object.extend({
   set: function(keyName, value) {
     this._super(keyName, value);
     if (keyName.indexOf('name.') > -1) {
       // a property of `name` has changed => notify observers of `name`
       this.notifyPropertyChange('name');
     }
   }
});

Demo: http://emberjs.jsbin.com/akEjubU/1/edit



来源:https://stackoverflow.com/questions/19245792/observe-properties-on-nested-object

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