Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

backbone.js

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.

like image 891
Ram Iyer Avatar asked May 14 '12 20:05

Ram Iyer


2 Answers

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().

like image 195
fguillen Avatar answered Oct 29 '22 21:10

fguillen


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);
};
like image 26
merlin Avatar answered Oct 29 '22 21:10

merlin