在我的主干应用程序中,我有一个由模型支持的视图,并且我将模型存储在一个集合中。页面上有几个这样的视图,一次只能选择一个。因此,我有另一个视图,其中包含这些视图的集合。当用户单击未聚焦的视图时,视图将模型的“聚焦”属性设置为 true。模型上的集合触发了一个更改事件,该事件由视图本身(将焦点类添加到其 $el)和ViewCollection 视图处理,该视图循环遍历集合中的所有视图并取消焦点中的任何焦点(除了刚刚点击的那个)。
当我以中等速度点击时,这一切都很好。但是,当我快速单击时,我发现模型的设置行为不一致。即,当我将模型的“focused”属性设置为true时,下一次点击事件显示该模型的“focused”属性仍然为false。
代码:
var M = Backbone.Model.extend({
defaults : {
"name" : "",
"focused" : true
}
}),
L = Backbone.Collection.extend({
model : M
}),
V = Backbone.View.extend({
events : {
"click .button" : "focus"
}
initialize: function() {
this.model.bind("change:focused", this.handleFocusChange, this)
},
focus: function() {
console.log("Focus: " + this.model.get("name") + ".focused = " + this.model.get("focused"));
if (this.model.get("focused")) {
return;
}
this.model.set({focused: true}); // triggers change event
this.model.save(this.model);
console.log("Focus: " + this.model.get("name") + ".focused = " + this.model.get("focused"));
},
unfocus: function() {
console.log("Unfocus: " + this.model.get("name") + ".focused = " + this.model.get("focused"));
if (!this.model.get("focused")) {
return;
}
this.model.set({focused: false}); // triggers change event
this.model.save(this.model);
console.log("Unfocus: " + this.model.get("name") + ".focused = " + this.model.get("focused"));
},
handleFocusChange: function(model, focused) {
if (focused) {
console.log("Handling focus change on " + this.model.get("name") + ", " + this.model.cid);
this.$('.button').addClass("focused");
} else {
console.log("Handling unfocus change on " + this.model.get("nickname") + ", " + this.model.cid);
this.$('.button').removeClass("focused");
}
}
}),
ViewCollection = Backbone.View.extend({
initialize : function(options) {
_.bindAll(this, 'initViews');
this._views = [];
this.collection.each(this.initViews);
},
initViews : function(model) {
var view = new V({
model : model
});
this._views.push(view);
view.model.bind("change:focused", this.focusChanged, this);
},
focusChanged: function(changed, focused) {
if (!focused) {
return;
}
_.each(this._views, function(view) {
if (view.model.id !== changed.id) {
view.unfocus();
}
});
}
})
以下是上述日志语句的输出:
Click
Focus: A.focused = false
Handling focus change on A, c10
Unfocus: B.focused = false
Unfocus: C.focused = false
Unfocus: D.focused = true
Handling ufocus change on D, c7
Unfocus: D.focused = false
Focus: A.focused = true <-- good!
Click
Focus: C.focused = false
Handling focus change on C, c9
Unfocus: B.focused = false
Unfocus: A.focused = false <-- bad!
Unfocus: D.focused = false
Focus: C.focused = true
正如你所看到的,我先点击了 A,然后点击了 C。changed 事件被触发,View 和 Collection 的行为都正常。然而,在第二次点击时,A 的“focused”属性在它应该为真时却是假的。同样,这只发生在我非常快速地单击视图时。当我以正常速度单击时,我无法重现此问题。
任何帮助将不胜感激!