I'm attempting what should be an elementary task with Backbone.js, and can't get it to work. I just want to perform a fetch operation on my model and have it update the view. Here's my code:
(function($) {
var HomeModel = Backbone.Model.extend({
defaults: {
lead: "not logged in",
},
url: 'test.php'
});
var HomeView = Backbone.View.extend({
initialize: function() {
this.model = new HomeModel();
this.model.bind("change", this.render);
this.model.fetch();
},
el: $("#content"),
render: function() {
this.$el.html(this.model.get("lead"));
}
});
var homeView = new HomeView();
})(jQuery);
I can see "test.php" loading successfully, but the render function never gets called.
What am I missing?
How did you see what "test.php" loaded succesfully? Maybe an AJAX request is succesful, but a response is not a valid JSON? Try to add success and error callbacks to the fetch call: this.model.fetch({success: function (resp) { console.log('success: %o', resp) }, error: function (er) { console.log('error: %o', er) });
I think I have the correct answer. You are referring to this in your render function, but the context of this is the event and not your class. You should therefore use underscore's bindAll function to bind the class to the function's internals. Like so:
var HomeView = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render'); // bind 'this' in 'render'
this.model = new HomeModel();
this.model.bind("change", this.render);
this.model.fetch();
},
});
Otherwise this.el does not exist, or it is wrong at least, and fails quietly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With