以下是我作为骨干代码的内容:
myEventModel = Backbone.Model.extend({});
var view_one = Backbone.View.extend({
initialize : function(){
myEventModel.on('change:someChange',function(){alert('Change observed for view one')});
}
render: function(){ $('body').append('view one')}
});
var view_two = Backbone.View.extend({
initialize : function(){
myEventModel.on('change:someChange',function(){alert('Change observed for view two')})
}
render: function(){ $('body').append('view two')}
});
所以我有两个视图听全局模型事件。所以在控制台中,我做
myEventModel.set({'someChange':new Date().getTime()});
我应该看到两个警报。但我不是。
答案 0 :(得分:0)
我对你的小提琴进行了一些修改:http://jsfiddle.net/ya4t1c24/1/
首先应创建模型和视图,然后触发事件。
myEventModel = Backbone.Model.extend({});
var view_two = Backbone.View.extend({
initialize : function(){
model.on('change:someChange',function(){alert('Change observed for view one')})
}
});
var view_one = Backbone.View.extend({
initialize : function(){
model.on('change:someChange',function(){alert('Change observed for view two')})
}
});
var model = new myEventModel;
var var_view_one = new view_one({model: model})
var var_view_two = new view_two({model: model})
model.set({'someChange':new Date().getTime()});
答案 1 :(得分:0)
您正在将视图/模型的定义与创建这些类型的对象混合在一起。
定义模型后,应创建该类型的对象:
var myEventModel = Backbone.Model.extend({});
var myEventModelInstance = new myEventModel();
然后在您的视图中,您希望侦听从对象而不是从模型定义中触发的事件,因此您应该更改视图,如下所示:
var view_one = Backbone.View.extend({
initialize : function(){
myEventModelInstance.on('change:someChange',function(){alert('Change observed for view one');})
}
});
var view_two = Backbone.View.extend({
initialize : function(){
myEventModelInstance.on('change:someChange',function(){alert('Change observed for view two');})
}
});
最后,您需要在更改模型对象之前创建视图对象,因为视图对象将对事件做出反应,而不是视图定义:
var viewOneInstance = new view_one();
var anotherViewOneInstance = new view_one();
var viewTwoInstance = new view_two();
myEventModelInstance.set({'someChange':new Date().getTime()});
使用上面的代码,您会看到2条带有'Change observed for view one'
消息的提醒,因为创建了2个view_one
个对象,并且单个提醒消息'Change observed for view two'
为view_two
} object已创建。