Search code examples
javascriptjqueryajaxbackbone.jsbackbone-views

Reload Backbone.View after Ajax request.How?


i've got ajax request in Backbone.View to change collection:

change: function(model, options){
me = this;
$.ajax({
    url: ajaxurl,
    type: 'post',
    data: {
        action: 'getShortcode',
        shortcode: model.attributes.shortcode
    },
    success: function (data) {
       me.$el.find('section:eq(' + model.collection.indexOf(model) + ')').replaceWith(data);
       me.add( model, model.collection );
    }
});
}

But after ajax request, my another Backbone.View (which call this ajax via triggers) don't work again, how a can "reload" my another Backbone.View after ajax, to force triggers call ajax again? thx!


Solution

  • You should use a Backbone.Model . If your model is already a Backbone.Model, just use model.set( anObjectWithTheChanges ) and that will trigger a change event in the model.

    Then, just add some code in your view's initialize function to listen to the changes in your model. Something like:

    this.listenTo( this.model, 'change', this.render);
    

    where render is the method in your view in charge of the refresh.