![](/img/trans.png)
[英]Backbone.js: How do I identify the model of the parent view upon an event?
[英]Backbone.js perform Model fetch upon View submit event
在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:有什么方法可以编写Router并让其侦听View的Submit事件?
///in my Backbone.Router
this.listenTo(this.view, 'submit', this.onFormSubmit);
...
onFormSubmit: function(){
console.log('caught button push!');
},
不幸的是,以上方法无效。
我自己找到了解决方案:
我定义了一个新模型:
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);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.