Backbone.js在View提交事件时执行Model fetch

Backbone.js perform Model fetch upon View submit event

本文关键字:执行 Model fetch 事件 提交 js View Backbone      更新时间:2023-09-26

在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:有没有一种方法我可以写一个路由器,让它听我的视图的提交事件?

  ///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);
    }
});