user2564522
user2564522

Reputation: 13

backbone.js fetch json success will not hit

i use fetch from backbone.js to load a json model but success will not hit.

var DialogModel = Backbone.Model.extend({
    url : function() {
        return '/messages/getDialog';
    },
    parse : function(res) { 
        return res.dialog;
    }
});

var DialogView = Backbone.View.extend({
    el: $("#page"),
    initialize: function() {
        var onDataHandler = function() {
            this.render();
        };
        this.model = new DialogModel();
        this.model.fetch({ success : onDataHandler});
      },
    render: function(){
        var data = {
                dialogModel : this.model
              };
        var form = new Backbone.Form({
             model: data
        });
        $(this.el).html(form.render().el);
    }
});

What happens now: DialogView initialize is called. this.model.fetch is called but the onDataHandler function will not be hit if success. /messages/getDialog throws a json file back. The json file is loading well as i can see in the network browser.

Thanks for your help! Oleg

Upvotes: 1

Views: 439

Answers (2)

Travis Webb
Travis Webb

Reputation: 15028

Even better is to listen for an event:

this.model.on("sync", this.render).fetch();

I ran across this question while looking for something else, but the currently accepted answer drives me nuts. There's no good reason to be sprinkling this and that all over your code. Backbone (underscore) includes a context parameter that you can bind to.

that = this makes no sense. If you must implement obsolete 2007-era Crockford patterns, then say var self = this. Saying that = this is like saying left = right. Everyone Stop.

Upvotes: 0

biril
biril

Reputation: 1995

The problem you're having is due to a typical JS gotcha and not related to Backbone itself. Try

var that = this;
this.model.fetch({ 
    success : function () {
        that.render();
    }
});

The way you're currently passing onDataHandler is problematic as it will cause this to refer to the global object instead of the DialogView, when the function is called.

This fiddle demonstrates the problematic version vs one that works.

(You may also want to take a look at JS strict mode which can shield you from this type of errors.)

Upvotes: 1

Related Questions