【问题标题】:Backbone not firing render event骨干网未触发渲染事件
【发布时间】:2013-03-27 13:14:29
【问题描述】:

我尝试创建两个视图并在不同情况下更改集合。我不知道如何设置 this.collection.bind 以便在每次集合更改时引发事件渲染。

在 3 种情况下,我希望视图 BusinessListView 触发 render

  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

我希望在 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();
});

【问题讨论】:

  • 不更改收款电话重置事件?我希望如果我手动更改集合(仅在此示例中)会调用渲染。
  • 删除了我的最后一条评论,因为我猜它是不正确的。您的 jsfiddle 显示渲染方法已运行。
  • 通过创建一个新对象,监听器消失了。所以你只是不听新的。

标签: events backbone.js view collections reset


【解决方案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/

【讨论】:

  • 它也没有触发 this.render() 。这条线(this.businesslist.collection)是故意存在的,我想看看如何使用不同的方法来修改集合。你能 fork jsfiddle 来展示工作示例吗?
  • Fiddle 添加到帖子底部
  • 谢谢,效果很好。我需要做什么才能从 SearchLocation 视图调用集合 5,6?
  • 通常像 sendData 这样的东西是事件驱动的。通常,您永远不会在初始化时调用 sendData,而是作为事件/回调的结果。 jsfiddle.net/aXJ9x/2 模拟此类事件。在这种情况下,我从 run 中调用了 sendData,只是为了让生活更轻松。
猜你喜欢
  • 1970-01-01
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多