在Backbone.View中,我有一个表单。提交后,我想执行model.fetch()。我如何以适当的Backbone.js MVC方式解决这个问题?
方法A,看起来很糟糕。//in my Backbone.View:
events: {'submit form#frm-destination': 'setDestination'},
setDestination: function(event){
event.preventDefault();
var destination = $('#destination').val();
this.model.fetch({
data : {
address : destination,
}
});
},
方法B: 有没有办法可以编写路由器并让它听取我的View的提交事件?
///in my Backbone.Router
this.listenTo(this.view, 'submit', this.onFormSubmit);
...
onFormSubmit: function(){
console.log('caught button push!');
},
不幸的是,上述情况不起作用。
答案 0 :(得分:0)
我自己找到了解决方案:
我定义了一个新模型:
var DestinationModel = Backbone.Model.extend({});
在我的路由器中,我有:
intialize: function(){
_.bindAll(this,'onDestinationChange');
this.modelToFetchModel = newMyModel();
this.destinationModel = new DestinationModel();
this.destinationView = new DestinationView({ model : this.destinationModel });
this.listenTo(this.destinationModel, 'change', this.onManualDestination);
},
onDestinationChange: function(model){
this.modelToFetchModel.fetch({ data : { address : model.get('destination') } });
}
我的视图看起来像这样:
var DestinationView = Backbone.View.extend({
events: {'submit form#frm-destination': 'setDestination'},
initialize: function(){
_.bindAll(this,'setDestination');
}
setDestination: function(event){
event.preventDefault();
var destination = $('#destination').val();
this.model.set('address',destination);
}
});