如何在模型对象上观察*all*属性更改?

Mar*_*ten 16 ember.js

我有一个从JSON对象构建的模型.

// extend the json model to get all props
App.Model = Ember.Object.extend(window.jsonModel);
Run Code Online (Sandbox Code Playgroud)

我希望在更新任何内容时自动保存模型.有什么方法可以为整个模型添加观察者吗?

编辑://添加我目前的解决方案

现在我做:

// XXX Can't be right
for (var prop in window.jsonModel) {
    if (window.jsonModel.hasOwnProperty(prop)) {
        App.model.addObserver(prop, scheduleSave);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个很大的形式,这意味着我增加了大量的观察者 - 它看起来效率很低.

一个萤火虫断点Ember.sendEvent()揭示了有App.model.lastName:change被发送的事件.我可以在那里进行拦截,但希望有正式的方法.

Shi*_*nko 8

你可以绑定到isDirty子类的属性DS.Model.在isDirty从改变时模特属性的一个改变.它不适用于所有情况,因为它只会更改一次,直到重置或提交,但对于您的情况 -

我希望在更新任何内容时自动保存模型.有什么方法可以为整个模型添加观察者吗?

它可能工作正常.


Mat*_*ttK 2

来自文章:

autosave: function(){
    this.save();
}.observes('attributes'),


save: function(){
  var self = this,
    url = this.get('isNew') ? '/todos.json' : '/todos/'+this.get('id')+'.json',
    method = this.get('isNew') ? 'POST' : 'PUT';

  $.ajax(url, {
    type: 'POST',
    // _method is used by Rails to spoof HTTP methods not supported by all browsers
    data: { todo: this.get('attributes'), _method: method },
    // Sometimes Rails returns an empty string that blows up as JSON
    dataType: 'text',
    success: function(data, response) {
      data = $.trim(data);
      if (data) { data = JSON.parse(data); }
      if (self.get('isNew')) { self.set('id', data['todo']['id']); }
    }
  });
},

isNew: function(){
   return !this.get('id');
}.property('id').cacheable(),
Run Code Online (Sandbox Code Playgroud)