我有一个关于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.
但这只是为了逐个取消个别属性。
有人有想法吗?
Gretz,
答案 0 :(得分:7)
来自Backbone网站:
clearmodel.clear([options])
从模型中删除所有属性,包括id属性。 除非作为选项传递静音,否则会触发“更改”事件。
所以我会这样做:
myModel.clear();
如果要保留属性,为什么不迭代所有属性并手动设置它们?
$.each(this.model.attributes, function(index, value){
// set them manually to undefined
});
答案 1 :(得分:3)
我知道这是一篇旧文章,但我最近遇到了一个类似的问题 - 主要是,如果你一个一个地取消设置,你会得到多个change
事件,模型处于中间状态每一个人。要允许在事后触发的相应更改事件中发生这种情况,您必须逐个静默地取消它们,然后在取消设置后手动触发每个事件的更改事件。但是,如果您查看Backbone代码,您会发现unset
方法实际上只是对set
的调用,选项中包含{unset:true}
。所以你应该能够做到这一点:
model.set({ attr1: undefined, attr2: undefined, attr3: undefined }, { unset: true })
我还没有在实践中尝试过,但它绝对应该在理论上运作。您将为每个属性获得一系列change
个事件,在所有未设置完成后。这种方法稍微超出推荐路径,因为它使用来自Backbone源的未暴露逻辑,但由于此特定代码hasn't changed in a few years(实际上在此之前似乎支持为set
选项),它应该是安全的并且继续使用。
答案 2 :(得分:1)
没有内置方法来设置所有属性未定义,同时保留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}