Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make backbone.js 'fetch' auto-update the view

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?

like image 811
McGarnagle Avatar asked Dec 20 '25 05:12

McGarnagle


2 Answers

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) });

like image 57
theotheo Avatar answered Dec 21 '25 20:12

theotheo


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.

like image 45
Mosselman Avatar answered Dec 21 '25 19:12

Mosselman