【问题标题】:Ember Binding or Observable to Null Out Other Value When SetEmber 绑定或 Observable 在设置时将其他值设为空
【发布时间】:2014-10-31 18:24:42
【问题描述】:

我的用户模型school_idschool_name 中有两个属性,因为如果我提供的列表不够,我允许用户指定他们自己的学校。这对于User 应该是通用的。 Ember 文档看似建议绑定,但只提供别名值或需要相同值的值。 Observables 似乎很合适,但什么是最好的以及如何?理想情况下,我想在模型级别指定它。

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

我想要的是,当我设置schoolName 时,school 设置为空,而当设置school 时,schoolName 设置为空。

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

【问题讨论】:

    标签: ember.js binding key-value-observing


    【解决方案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')
    });
    

    我还没有测试过所有的场景,但这可以按预期工作:

    _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.
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 2015-12-18
      • 2022-08-24
      • 2019-01-27
      相关资源
      最近更新 更多