2014-10-31 64 views
0

我在我的用户模型school_idschool_name中有两个属性,因为如果我提供的列表不允许用户指定自己的学校。这应该是通用的User。 Ember文档似乎提供了绑定,但只提供别名值或需要相同值的值。观察对象似乎是合适的,但是最好的和如何?理想情况下,我想在模型级别指定它。灰烬绑定或可观察空置其他值设置

Models.User = DS.Model.extend({ 
    schoolName: DS.attr("string"), 
    school: DS.belongsTo("school", {async: true }) 
}); 

我想要的是,当我设置schoolNameschool设置为null,当school设置,schoolName设置为null。

的我后Rails的模式相当于:

class User < ActiveRecord::Base  
    def nces_high_school_id=(value) 
    write_attribute(:school_name, nil) 
    write_attribute(:school_id, value) 
    end 
    def school_name=(value) 
    write_attribute(:school_id, nil) 
    write_attribute(:school_name, value) 
    end 
end 

回答

1

您可以添加观察员的属性,对变化做出反应(http://emberjs.com/api/classes/Ember.Observable.html#toc_observing-property-changes)。

你需要这样的事情,来完成你想要的东西:

App.User = DS.Model.extend({ 
    schoolName: DS.attr("string"), 
    school: DS.belongsTo("school", {async: true }), 

    _suspendValueChange: false, 

    schoolUpdateObserver: function() { 
     if (this.get('school') && this.get('_suspendValueChange') == false) { 
      this.set('_suspendValueChange', true); 
      this.set('schoolName', undefined); 
      this.set('_suspendValueChange', false); 
     } 
    }.observes('school'), 

    schoolNameUpdateObserver: function() { 
     if (this.get('schoolName') && this.get('_suspendValueChange') == false) { 
      this.set('_suspendValueChange', true); 
      this.set('school', undefined); 
      this.set('_suspendValueChange', false); 
     } 
    }.observes('schoolName') 
}); 

我还没有测试所有senarios,但按预期工作:

_this = this; 
this.store.find('school', 1).then(function(school) { 
    var user = _this.store.createRecord('user'); 
    user.set('school', school); // => schoolName is set to undefined, and school is set to the school record. 
    user.set('schoolName', 'test'); // => school is set to undefined, and schoolName is set to 'test'. 
    user.set('school', school); // => schoolName is set to undefined, and school is set to the school record. 
}); 
+0

我知道这是迟到了,但感谢! – Michael 2015-01-07 04:22:04