Reputation: 13
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
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
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