2012-02-08 134 views
16

我有一个从JSON对象构建的模型。如何观察模型对象上的所有属性更改?

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

我想在更新任何内容时自动保存模型。有什么方法可以将观察者添加到整个模型中?

编辑://添加解决方案,我现在去

现在我做:

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

这是一个大的形式,这意味着我将观察员吨 - 它似乎很低效。

一个Firebug的断点Ember.sendEvent()显示,有叫App.model.lastName:change事件被发送。我可以在那里进行拦截,但希望有一种正式的方式。

回答

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(), 
+0

的问题是在attributes'必须显式绑定到*在我的模型中的每个*属性(看到的计算性能'在原始文章中) - 这是我不想要的。 – 2012-02-09 00:59:42

2

我有同样的要求,并没有找到合适的答案,我实现了一个。

试试这个:https://gist.github.com/4279559

本质上讲,你要观察的所有属性必须是一个混合Ember.Stalkable的对象。你可以看到,对象的属性“项。@属性”(或者,如果你直接在Stalkable烤观察员,“@properties”单独的作品。“@ownProperties”,“@initProperties”和“@prototypeProperties”也行,并且是指(属性所特有的一个实例,并且在任何原型没有定义),(其被定义为创建()调用的一部分属性),以及(被定义为类定义的一部分属性)。

在你的观察,如果你想知道什么性质改变和调用的处理,物业“modifiedProperties”,一个阵列,将可与改变属性的名称。

8

您可以绑定到isDirty财产DS.Model的子类从真正当模特属性的变化之一种变化。它不会对所有的情况下更好地服务,因为它仅更改一次,直到复位或承诺,但对你的情况 -

我想什么时候更新自动保存模型。有什么方法可以将观察者添加到整个模型中?

可以正常工作。

+1

如果您不使用Ember Data,该怎么办? – 2015-11-23 09:53:38

0

我创建了一个可以作为一个依赖密钥的虚拟财产_anyProperty

import Ember from 'ember'; 

Ember.Object.reopen({ 

    // Virtual property for dependencies on any property changing 
    _anyPropertyName: '_anyProperty', 
    _anyProperty: null, 

    propertyWillChange(keyName) { 
    if (keyName !== this._anyPropertyName) { 
     this._super(this._anyPropertyName); 
    } 
    return this._super(keyName); 
    }, 

    propertyDidChange(keyName) { 
    if (keyName !== this._anyPropertyName) { 
     this._super(this._anyPropertyName); 
    } 
    return this._super(keyName); 
    } 

}); 
相关问题