我可以在模型中监听一个对象的任何更改吗? 我知道如何监听模型更改,但我只需要在模型和视图中监听对象。
var view = Backbone.View.extend({
func: {},
initialize: function () {
this.listenTo(this.func, 'change', function(select){
console.log(select.changed) //NEED TO SHOW ON ADDING ANY DATA TO this.func
})
this.func['asd'] = 'asdasd';
}
})
答案 0 :(得分:10)
这正是模型的用途 - 不仅可以从服务器获取数据,还可以在应用程序周围传递数据。
当您想要了解某些数据的更改时,您不会创建自定义变量,而是使用属性。
var MyModel = Backbone.Model.extend({
initialize: function() {
// Listen to changes on itself.
this.on('change:asd', this.onAsdChange);
},
onAsdChange: function(model, value) {
console.log('Model: Asd was changed to:', value);
}
});
var MyView = Backbone.View.extend({
initialize: function() {
// Listen to changes on the model.
this.listenTo(this.model, 'change:asd', this.onAsdChange);
},
onAsdChange: function(model, value) {
console.log('View: Asd was changed to:', value);
}
});
var myModel = new MyModel();
var myView = new MyView({
model: myModel
});
myModel.set('asd', 'something');
myModel.set('asd', 'something else');
答案 1 :(得分:0)
您可以使用
收听模特的变更事件 initialize: function(){
this.listenTo(this.model, 'change', function(select){
console.log(select.changed) //NEED TO SHOW ON ADDING ANY DATA TO this.func
});
}