问题描述
如果在初始化dialogview时使用模型属性的对象数组初始化集合.然后,允许用户编辑列表的对话框视图会通过调用模型集来更新这些模型值.单击对话框的确定"按钮时,骨干网是否提供一种方法来仅获取自创建/初始化集合以来已更改的那些模型的列表?
If I initialize a collection with an array of objects for the model attributes when a dialogview is initialized. Then the dialog view that lets the user edit the list updates those model values with calls to model set. When the dialog's ok button is clicked, Does backbone provide a way to get the list of only those models that changed since the collection was created/initialized?
推荐答案
有多种吸引人的模型方法:
There are various model methods that look tempting:
但不要上当,那些仅在触发"change"
事件时适用:
But don't be fooled, those only apply while a "change"
event is being triggered:
因此在事件被触发和处理后它们就没用了.
so they're useless after the event has been triggered and handled.
我认为您必须跟踪哪些模型改变了自己.自从
I think you have to track which models have changed yourself. You can do this on the collection itself without too much effort since
并且该集合可以绑定到其自己的事件.例如,您的收藏夹中可能包含以下内容:
and the collection can bind to its own events. For example, you could have something like this in your collection:
Backbone.Collection.extend({
initialize: function() {
this.delta = { };
this.on('change', this._a_model_has_changed);
},
changed_models: function() {
return _.chain(this.delta).values();
},
_a_model_has_changed: function(m) {
this.delta[m.id] = m;
}
});
然后,您可以通过调用collection.changed_models()
来获取已更改的模型.您还想监听其他事件,以便在删除模型或与服务器同步模型时可以更新this.delta.以上仅供参考.如果您不希望返回Underscore对象,则可以使用以下对象:
Then you could get the models that have changed by calling collection.changed_models()
. You'd want to listen for other events as well so that you could update this.delta when models are deleted or synced with the server; the above is just for illustration. If you didn't want an Underscore object returned you could use this instead:
changed_models: function() {
return _(this.delta).values();
}
但是能够使用collection.changed_models().each(function() { ... })
很方便.
演示: http://jsfiddle.net/ambiguous/8PQh9/
您还可以让模型通过模型上的类似集合来跟踪其自身的脏污程度.然后您可以执行以下操作:
You could also let the models track their own dirtiness through a similar set on the models. Then you could do something like this:
collection.filter(function(m) { return m.is_dirty() });
当然,如果更改了模型,is_dirty
将返回true.
where, of course, is_dirty
would return true if the model had been changed.
这篇关于如何从集合中获取自构造以来已发生更改的模型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!