Ram Iyer
Ram Iyer

Reputation: 1564

Backbone.js Sync is not triggering any events on the model

I have a very simple setup...

A route is setup that calls a modal dialog using bootstrap. The headerView calls a method when a menu is clicked -

menuClick: function(e){
    e.preventDefault();
    if (!this.myView) {
        this.myView= new MyView({model: new MyModel()});
    }
    this.myView.render();
},

In the MyView I call bind in the initialize

initialize: function(){
    this.model.bind('sync', function(model){ alert('test view')});
}

And call Backbone.sync in a button click event:

var response = Backbone.sync('read', this.model, {
    success: function(data, textStatus, jqXHR) { alert('success'); },
    error: function(data, textStatus, jqXHR){ alert(fail); }
});

The alert inside the sync gets called...but the alert in the bind command in the initialize never gets called. Tried moving the bind inside the model, moving it out, also tried sync:fail, sync:done. No success.

Upvotes: 5

Views: 6150

Answers (2)

fguillen
fguillen

Reputation: 38838

Not any event is triggered because you didn't say so. You are passing explicit success and error callbacks which are the ones that have to be in charge of triggering the events.

The native Backbone.sync calls from the high layer commands as save, create, fetch receive success and error callbacks those trigger the events, but you are using your own so this native behavior is obviated.

For example in the Model.save, in the Model.destroy and so on.

But, as I said in a previous comment, you really should think if you really need to call Backbone.sync directly instead of using more higher layer methods like Model.fetch().

Upvotes: 4

merlin
merlin

Reputation: 34

Try to implement the Backbone.sync like this:

var sync = Backbone.sync;
Backbone.sync = function (method, model, options) {
    var success = options.success;
    options.success = function (resp, status, xhr) {
        //Your logic goes here
        console.log('succeed');
        if (success) success(resp, status, xhr);
    };
    options.error = function (xhr, ajaxOptions, thrownError) {
        console.log('failed');
    }
    sync(method, model, options);
};

Upvotes: 2

Related Questions