Search code examples
javascriptbackbone.jsbackbone-views

How to watch for variable changes in Backbone


I have a view which has a property called headerClass which I define at the top of the view and in various methods I change the value by doing this.headerClass = 'new value'.

But how can I watch for changes to this variable? I tried add this.headerClass.on("change", this.render, this); but I get an error when doing this.

Below is my code

MyView = Backbone.View.extend({
    el: $(".header"),
    template: _.template($("#header-template").html()),
    headerClass: 'normal',

    initialize: function () {
        this.render();

        //This doesn't seem to work
        this.headerClass.on("change", this.render, this);
    },

    render: function () {
        this.$el.html(this.template({headerClass: this.headerClass}));
        return this;
    },

    changeClass: function () {
        //When the value changes I want to re-render the view
        this.headerClass: 'fluid';
    }
});

Solution

  • I would suggest implementing a sort of setter function for this attribute. Every time this function is called with a new value, an event is triggered by the view.

    set_headerClass: function (value) {
        this.headerClass = value;
        this.trigger("changed:headerClass");
    }
    

    You can now add a listener to the view and watch for changes:

    initialize: function () {
        ...
        // Will re-render the view when the event is detected.
        this.on("changed:headerClass", this.render, this);
    },
    

    When you want to change the headerClass value, you would do so by calling the setter function:

    changeClass: function () {
        this.set_headerClass('fluid');
    }