Backbone没有触发渲染事件

时间:2013-03-27 13:14:30

标签: events backbone.js view collections reset

我尝试在不同情况下创建两个视图并更改集合。我不知道如何设置this.collection.bind,因此它会在每次集合更改时引发事件呈现。

有三种情况我希望查看BusinessListViewrender

  1. this.businesslist.collection = new Businesses([{ name: '1'}, { name: '2' }]);
  2. this.businesslist.set();调用this.collection = new Businesses([{ name: '3'}, { name: '4' }]);
  3. this.search_location = new SearchLocation();这是不同的视图,然后发送集合以查看BusinessListView
  4. 我期待在1和2的控制台上看到数据,但它不起作用。如果我手动添加.render(),我可以看到集合已经改变。你能解释一下它是如何工作的吗?

    更新

    感谢Alex,这是一个完全可行的解决方案:

    http://jsfiddle.net/feronovak/RAPjM/

    var App = {
        run: function() {
            this.businesslist = new BusinessListView(); 
            this.businesslist.collection = new Businesses([{ name: '1'}, { name: '2' }]);
            // this.businesslist.render(); // uncomment to see collection change 
            this.businesslist.set();
    
            this.search_location = new SearchLocation();
        }
    };
    
    Business = Backbone.Model.extend({});
    Businesses = Backbone.Collection.extend({
        model:  Business
    });
    
    BusinessListView = Backbone.View.extend({
        initialize: function(options) {
            this.collection = new Businesses();
            this.collection.bind("reset", this.render(), this);
        },
        render: function() {
            console.log(this.collection.toJSON());
        },
        set: function()
        {
            this.collection = new Businesses([{ name: '3'}, { name: '4' }]);
            // this.render(); // uncomment to see collection change 
        }
    });
    
    SearchLocation = Backbone.View.extend({
        el: "#search",
        initialize: function() {
            this.sendData();
        },
        sendData: function() {
            //  Send [{ name: '5'}, { name: '6' }] to this.businesslist  = new Businesses([{ name: '5'}, { name: '6' }]);
        }
    });
    
    $(document).ready(function(e) {
        App.run();
    });
    

1 个答案:

答案 0 :(得分:1)

您继续将this.collection引用设置为不同的实例。它不会“重置”,因为你从未真正重置初始化中引用的对象。

而不是:

set: function()
    {
        this.collection = new Businesses([{ name: '3'}, { name: '4' }]);
    }

尝试:

set: function()
    {
        this.collection.reset([{ name: '3'}, { name: '4' }]);
    }

并在运行中删除:

this.businesslist.collection = new Businesses([{ name: '1'}, { name: '2' }]);

此处示例:http://jsfiddle.net/aXJ9x/1/