骨干:我应该听哪些事件

时间:2014-02-19 08:53:04

标签: backbone.js

我创建了一个视图,它正在收听一个集合。这个系列的模型一下子就被替换了。我希望尽可能少地呈现视图。

查看:

BoxContent = Backbone.View.extend({

    initialize: function(options) {
        console.log("BoxContent initializing");
        this.el = options.el;
        this.collection = options.collection;
        this.collection.on("add", this.update, this);
        this.collection.on("reset", this.update, this);
    },

    update: function(){
        this.render();
    },

    render: function() {
        document.getElementById('boxContentHeader').innerHTML = localStorage.activeBox;
        console.log("BoxContent rendering");
        var temp = _.template(maincontemp,{boxFolder: this.collection});
        this.$el.empty();
        this.$el.append(temp);
        this.$el.trigger("create");
    },

    reset: function()
    {
        this.render();
    },

    close: function(){
        //console.log("off-logging clickListener");
        //this.collection.off();
        //$(this.el).off();
    }
});

要更新集合,我创建了一个模型数组,重置集合并将新数组放入集合中。我需要听重置,以便渲染一个空集合。 我不从restful-server获取数据。

是否还有其他方法可以收听对集合的更改?

编辑:

还有一个问题:虽然我只是在集合中添加了一个模型数组,但是主干是否为此数组中的每个模型调用了add事件?

1 个答案:

答案 0 :(得分:2)

查看文档中的Catalog of Events。您可以侦听参数中包含参数collection的所有事件。

  • add - (model, collection, options) - 将模型添加到集合中时。
  • remove - (model, collection, options) - 从集合中删除模型时。
  • reset - (collection, options) - 当集合的全部内容被替换时。
  • sort - (collection, options) - 重新整理集合时。
  • destroy - (model, collection, options) - 模型被销毁时。
  • request - (model_or_collection, xhr, options) - 当模型或集合向服务器发起请求时。
  • sync - (model_or_collection, resp, options) - 当模型或集合已成功与服务器同步时。
  • error - (model_or_collection, resp, options) - 当模型或集合对远程服务器的请求失败时。
  • all - 此特殊事件会触发任何触发事件,并将事件名称作为第一个参数传递。