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

标签 javascript backbone.js

我正在尝试使用在 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/

相关文章:

javascript - Backbone.Marionette - 以某种方式收集 "missing"一些元素

javascript - Angular 5 - 另一个观察者内部的观察者循环 - 有效的方法

javascript - 从插件访问 Ember 环境配置(ENV)?

javascript - 使用 javascript 进行电话验证

ruby-on-rails-3 - 如何将原始 html 字符串属性嵌入到 .hamlc 模板中?

javascript - Backbone +r.js : Backbone is not defined

javascript - Struts 1在jsp中使用显示标签删除确认

javascript - 如何从backbone.js中的 View 渲染 View

javascript - 循环集合构建 View 主干

javascript - 检测从集合主干中删除的模型