Pattle
Pattle

Reputation: 6016

Backbone view not updating

I have the following Backbone view and when I intialize it I load my template

var ListView = Backbone.View.extend({
    el: $('.products'),
    template: _.template($('#products-template').html()),
    sortKey: 'id',
    events: {
        "click .sort": "sortProducts"
    },
    initialize: function() {
        _.bindAll(this, 'render', 'appendItem', 'loadMore');

        $(this.el).html(this.template({sortKey: this.sortKey}));
        this.collection = new List();
    },

    sortProducts: function(e) {
        this.sortKey = $(e.currentTarget).data('sort');
        e.preventDefault();
    },

In my view I echo out the value of sortKey

<%-sortKey %>

This works fine when I first load the page but when the sortKey changes when the sortProducts function is trigger the view doesn't update with the new value of sortKey.

I thought Backbone was meant to update the view automatically? Am I doing something wrong?

Upvotes: 1

Views: 1668

Answers (1)

Vic
Vic

Reputation: 8961

Backbone doesn't automatically update your view, you have to tell it to.

sortProducts: function(e) {
    this.sortKey = $(e.currentTarget).data('sort');
    e.preventDefault();
    this.render();
}

You can set up automatic update by listening to events:

// example of updating the view when the model changes
this.listenTo(this.model, 'change', this.render);

Also, you should move the template/render into the render function:

render: function () {
    this.$el.html(this.template({sortKey: this.sortKey}));
}

Upvotes: 1

Related Questions