简体   繁体   English

Backbone.js没有注册Model.hasChanged事件

[英]Backbone.js not registering Model.hasChanged event

I'm trying to get a View in Backbone.js to save when there's a 'change' event if (and only if) the data has changed. 我正在尝试在Backbone.js获取一个View,以便在存在“更改”事件时保存(如果(仅当)数据已更改)。

Long story short, I've a 'change' event set on the View that calls this: 长话短说,我在View上设置了一个'更改'事件,调用它:

function changed_event() {
  log.debug("Before: " + this.model.get('name')) // not 'contrived!'
  this.model.set({'name': 'contrived!'});
  log.debug("After: " + this.model.get('name')) // 'contrived!'

  if (this.model.hasChanged()) {
      alert("This is never called.");
  }
}

I'd like to know why the model.hasChanged() is false when clearly the model has been changed. 我想知道为什么当模型被更改时, model.hasChanged()false

I'm not sure what other information is necessary, but if there is more information that may be helpful please comment and I'll elaborate. 我不确定其他信息是否必要,但如果有更多可能有用的信息,请发表评论,我会详细说明。

Thank you for reading. 谢谢你的阅读。

By calling model.set , you are firing a change event. 通过调用model.set ,您将触发更改事件。 .hasChanged() returns true iff the model has changed since the last change event . .hasChanged()如果自上次更改事件后模型已更改,则返回true。 So it will return false since nothing changed since that change event. 所以它将返回false,因为自更改事件以来没有任何更改。 To get the behaviour you want, call .set with the silent option: this.model.set({'name': 'contrived!'}, {silent: true}) 要获得所需的行为,请使用silent选项调用.setthis.model.set({'name': 'contrived!'}, {silent: true})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM