我有一个关于 Backbone 的问题,如何将模型的所有属性设置为空?
unsetmodel.unset(attribute, [options])
Remove an attribute by deleting it from the internal attributes hash. Fires a "change" event unless silent is passed as an option.
但这仅用于一一取消设置各个属性。
任何人的想法?
格雷茨,
我有一个关于 Backbone 的问题,如何将模型的所有属性设置为空?
unsetmodel.unset(attribute, [options])
Remove an attribute by deleting it from the internal attributes hash. Fires a "change" event unless silent is passed as an option.
但这仅用于一一取消设置各个属性。
任何人的想法?
格雷茨,
从骨干网站:
clearmodel.clear([选项])
从模型中删除所有属性,包括 id 属性。除非将静音作为选项传递,否则触发“更改”事件。
所以我会做类似的事情:
myModel.clear();
如果要保留属性,为什么不遍历所有属性并手动设置它们呢?
$.each(this.model.attributes, function(index, value){
// set them manually to undefined
});
我知道这是一篇旧帖子,但我最近遇到了一个类似的问题 - 主要是,如果你一个接一个地取消设置,你会得到多个change
事件,每个事件的模型都处于中间状态。为了允许在随后触发的适当更改事件中发生这种情况,您必须一个接一个地静默取消设置它们,然后在取消设置后手动触发每个更改事件。但是,如果您查看 Backbone 代码,您会发现该unset
方法实际上只是对选项的set
调用{unset:true}
。所以你应该可以这样做:
model.set({ attr1: undefined, attr2: undefined, attr3: undefined }, { unset: true })
我还没有在实践中尝试过,但它绝对应该在理论上有效。在所有未设置完成后change
,您将获得每个属性的一系列事件。这种方法有点超出推荐的路径,因为它使用来自 Backbone 源的未公开逻辑,但由于这个特定代码在几年内没有改变(实际上在此之前似乎作为一个选项被支持),它应该安全使用并继续使用。set
没有内置方法可以设置所有未定义的属性,同时保留attributes
键。好消息是,您可以使用下划线单行轻松自己构建一个:
Backbone.Model.prototype.clearValues = function(options) {
this.set(_.object(_.keys(this.attributes), []), options);
}
然后所有模型都会有一个clearValues
方法:
var model = new Model({
id:1,
foo:'foo',
bar:'bar'
});
model.clearValues();
console.log(model.toJSON()); //-> {id: undefined, foo: undefined, bar: undefined}