【问题标题】:Ember Data: When does the "didLoad" event fire?Ember Data:“didLoad”事件何时触发?
【发布时间】:2013-04-22 02:41:29
【问题描述】:

Ember Data's documentation discusses different events in a model instance's lifecycle.
我希望每当模型实例的任何属性发生更改时都会触发 didUpdate 事件。但是我的实验没有显示这种行为。

这是一个 JS Bin 示例:http://jsbin.com/uziwam/9/edit
在该示例中,您可以看到我在“ren”模型实例上注册了处理程序:我为 didLoaddidUpdate 事件注册了处理程序(console.log(..) 消息)。

启动代码时,“ren's”didLoad 事件触发,这是预期行为。然后,当使用 GUI 编辑“ren's”属性时,不会触发 didUpdate 事件。这是(至少对我而言)出乎意料的行为。

我必须做什么才能让didUpdate 事件触发?

【问题讨论】:

    标签: ember.js ember-data


    【解决方案1】:

    当记录被有效保存时,didUpdate 事件被触发,这意味着你必须提交它,并且你的适配器已经确认了提交。

    要提交记录的更改,可以使用record.get('transaction').commit()。

    http://jsbin.com/uziwam/11/edit

    如果你想在属性改变时提交事务,你可以在上面放置一个观察者。

    App.User = DS.Model.extend({
      firstName: DS.attr("string"),
      lastName: DS.attr("string"),
    
      firstNameDidChange: function(){
        this.get('transaction').commit();
      }
    });
    

    如果您想针对每条记录的属性进行概括,您应该能够执行以下操作:

    App.User = DS.Model.extend({
      firstName: DS.attr("string"),
      lastName: DS.attr("string"),
    
      init: function(){
        this._super();
        this.eachAttribute(function(attributeName){
          this.addObserver(attributeName, this, this.commitRecord); 
        }, this);
      }
    
      commitRecord: function(){
        this.get('transaction').commit();
      }
    });
    

    http://jsbin.com/uziwam/14/edit

    【讨论】:

    • 感谢您的解释和工作示例! ...有没有一种简单的方法可以在属性更改时立即提交事务(...即不需要用户发起的save 操作)?
    猜你喜欢
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2014-02-22
    • 2013-01-05
    • 2020-01-19
    • 2018-09-08
    • 2015-07-08
    • 2015-08-20
    相关资源
    最近更新 更多