gpt4 book ai didi

javascript - backbone.js 的先前属性不是持久的

转载 作者:数据小太阳 更新时间:2023-10-29 05:48:48 24 4
gpt4 key购买 nike

我正在尝试使用在 Backbone 的模型中使用先前的 api 提到的示例。我已经粘贴了下面的例子

var bill = new Backbone.Model({
name: "Bill Smith"
});

bill.bind("change:name", function(model, name) {
alert("Changed name from " + bill.previous("name") + " to " + name);
});

bill.set({name : "Bill Jones"});

警报中的前一个值是 Bill Smith,这是正确的。但是如果我尝试通过调用在 Firebug 中访问它

bill.previous("name");

是 Bill Jones 而不是 Bill Smith。为什么会这样?我错过了什么?

最佳答案

好吧,如果您查看 Backbone 的源代码,您会发现 Backbone.Model 中的 _previousAttributes 属性在 ' change' 事件已被触发(在 change 方法中:this._previousAttributes = _.clone(this.attributes);)。

我想我以前在 Github 上看到过关于这种行为的问题;这出乎很多人的意料。

编辑:找到了;作者在 https://github.com/documentcloud/backbone/pull/373 中的引述:

I'm afraid that the current behavior is how things are supposed to work. Previous attributes are only available during the course of a "change" event. Without this, the entire notion of hasChanged() makes no sense.

If you're looking for more robust undo-like functionality, I'd recommend keeping a true list of previous versions of the model.

关于javascript - backbone.js 的先前属性不是持久的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7208393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com