我想将呼叫保存到我的服务器,所以我目前正在使用Model.save()
选项patch
和发送changedAttributes()
.
我想删除一个属性并添加一个新属性。Model.set()
/每次unset()
都会修改,这样我就不能将它与上述/方案一起使用。changedAttributes()
Model.save()
patch
我想我想简单地调用Model.set()
并传入一个对象,其中包含我希望取消设置undefined
的值以及我希望设置的值。
unset()
有没有一种方法可以让我set()
一次性获得changedAttributes()
?或者也许确定changedAttributes()
一组组合的操作?
// Currently
var m = new Backbone.Model({ "foo": "bar" });
m.unset("foo");
console.log(m.changedAttributes()); // { "foo": undefined }
m.set("baz", "bar");
console.log(m.changedAttributes()); // { "baz": "bar" }
console.log(m.attributes); // { "baz": "bar" }
// At this point, how do I get the combination of changed attributes? something like: { "foo": undefined, "baz": "bar" }?
// Is that even possible? Am I doing something horribly wrong?
//================================================================
// What (I think) I want is for Model.set() to remove attributes with values of undefined, so I only have to make one call and changedAttributes() will be pristine. Maybe with a option or something?
var w = new Backbone.Model({ "foo": "bar" });
w.set({ "foo": undefined, "baz": "bar" });
console.log(w.changedAttributes()); // { "foo": undefined, "baz": "bar" }
console.log(w.attributes); // I would like it to be { "baz": "bar" }, "foo" having been removed in the set() call.
//================================================================
// I was trying to avoid processing the objects by hand. I realize that I can do something like the following.
var h = new Backbone.Model({ "foo": "bar" });
var changes = { "foo": undefined, "baz": "bar" };
_.each(changes, function(val, key) {
if (_.isUndefined(val)) {
h.unset(key, { "silent": true });
} else {
h.set(key, val, { "silent": true });
}
});
h.trigger('change'); // Trigger a change event after all the changes have been done.
console.log(changes); // { "foo": undefined, "baz": "bar" }
console.log(h.attributes); // { "baz": "bar" }
上述代码在行动中的小提琴:http: //jsfiddle.net/clayzermk1/AmBfh/
大约一年前似乎已经对此主题进行了一些讨论https://github.com/documentcloud/backbone/pull/879。似乎我想要的功能在某个时候存在。
编辑:正如@dennis-rongo 指出的那样,我显然可以手动完成。重申我上面的问题:“Backbone 是否允许一次设置/删除属性?” 如果不是,该决定背后的理由是什么?Derick Bailey 创建了 Backbone.Memento ( https://github.com/derickbailey/backbone.memento ) 来处理属性状态,Backbone 上有几个与此场景密切相关的模型状态问题 ( https://github.com /documentcloud/backbone/pull/2360,有点相关:https ://github.com/documentcloud/backbone/issues/2316 ,高度相关:https ://github.com/documentcloud/backbone/issues/2301 )。
编辑 2:我不是在寻找手动解决方案,我可以让它或多或少地做我想要的(参见上面的示例代码)。我正在寻找当前设计的理由,并为此常见场景提供一个干净的示例 - 一次性设置和取消设置。
更新:在https://github.com/documentcloud/backbone/issues/2301中有一些关于这个主题的对话。我已经提交了一个拉取请求(https://github.com/documentcloud/backbone/pull/2368),试图鼓励对当前实现的讨论。
感谢所有发布答案的人!