骨干视图不更新

时间:2015-01-13 14:25:51

标签: javascript backbone.js

我有以下Backbone视图,当我初始化它时,我加载了我的模板

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

在我看来,我回应了sortKey的价值

<%-sortKey %>

我第一次加载页面时工作正常但是当sortProducts函数触发时sortKey发生更改时,视图不会使用新值sortKey更新。

我认为Backbone是为了自动更新视图?我做错了吗?

1 个答案:

答案 0 :(得分:1)

Backbone不会自动更新您的视图,您必须告诉它。

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

您可以通过收听事件来设置自动更新:

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

此外,您应该将模板/渲染移动到render函数:

render: function () {
    this.$el.html(this.template({sortKey: this.sortKey}));
}
相关问题