如何从不同的视图修改单个模型?
伪代码:
var myModel = Backbone.Model.extend({url: 'rest'});
var myCollection = Backbone.Model.extend({});
var myView1 = Backbone.Views.extend({
initialize: function() {
// sets a data in model so it can be use by second and third view
myModel().fetch();
},
events: {
'event': 'callSecondView',
'event': 'callThirdView'
},
callSecondView: function() {
// second view will use the current records in myModel that
// was created during initialization or from the modification
// of 1st or third view
new myView2({model: myModel})
},
callThirdView: function() {
// third view will use the current records in myModel that
// was created during initialization
// of 1st or third view
new myView3({model: myModel})
}
});
var myView2 = Backbone.Views.extend({
events: {
'event': 'modifyMyModel'
},
modifyMyModel: function() {
this.model.set(etc)
// Modifying model here should affect the 1st and 3rd view's model
}
});
var myView3 = Backbone.Views.extend({
events: {
'event': 'modifyMyModel'
},
modifyMyModel: function() {
this.model.set(etc)
// Modifying model here should affect the 1st and 2nd view's model
}
});
这可能吗?或者我应该只在一个视图中组合所有三个视图?(这将导致怪物视图)
答案 0 :(得分:2)
看起来非常难看为什么不首先获取模型然后根据需要创建多少个视图:
var MyModel = Backbone.Model.extend({url: '/api/data'});
var View1 = Backbone.View.extend({});
var View2 = Backbone.View.extend({});
var View3 = Backbone.View.extend({});
var myModel = new MyModel();
myModel.fetch({
success: function(){
window.myView1 = new View1({model:myModel});
window.myView2 = new View1({model:myModel});
window.myView3 = new View1({model:myModel});
}
});
// in console
myView1.model == myModel
true