简体   繁体   中英

Backbone.js perform Model fetch upon View submit event

In a Backbone.View, I have a form. Upon submit, I want to perform a model.fetch(). How do I go about this, in proper Backbone.js MVC fashion?

Approach A, seems like bad style.

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

Approach B: Is there a way I can write a Router and have it listen to the submit event of my View?

  ///in my Backbone.Router
  this.listenTo(this.view, 'submit', this.onFormSubmit);
  ...
  onFormSubmit: function(){
        console.log('caught button push!');
  },

The above doesn't work, unfortunately.

I found a solution myself:

I defined a new Model:

var DestinationModel = Backbone.Model.extend({});

In my Router, I have:

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

And my View looks like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM