【问题标题】:Backbone Paginator Collection not triggering render on Reset主干分页器集合未在重置时触发渲染
【发布时间】:2013-02-03 20:31:28
【问题描述】:

我有一个 Backbone Paginator 集合:

    var ExercisesCollection = Backbone.Paginator.requestPager.extend({

        model: ExerciseModel,

        paginator_core: {
            url: "/exercises"
        },

        paginator_ui: {
            firstPage: 1,
            currentPage: 1,
            perPage: 10,
            totalPages: 10
        },

        server_api: {
            "filter": "",
            "categories": "",
            "top": function() { return this.perPage; },
            "skip": function() { return this.currentPage * this.perPage; }
        },

        parse: function (response) {
            this.totalPages = response.meta.totalPages;
            return response.data;
        }

    });

我像这样在主干视图中使用它:

var Exercises = Backbone.View.extend({

    initialize: function () {
        this.collection = new ExercisesCollection();
        this.collection
            .on( "reset", this.render, this )
            .on( "change", this.render, this);
        this.collection.goTo( 1 );
    },

    render: function() {
        alert("bah!");
    }
});

通过查看网络活动,我可以看到它正在向服务器发送请求并接收到适当的响应。但是它从不调用渲染函数。重置和更改事件似乎不起作用。

任何想法我做错了什么?

谢谢

【问题讨论】:

  • this.collection 你定义了吗?
  • 是的 this.collection 是 Paginator Collection 的一个实例
  • .on("add", this.render, this) ?
  • 试过了 - 不幸的是没有。
  • 我不熟悉Backbone.Paginator,你能用普通的骨干集合测试一下吗?

标签: javascript jquery backbone.js


【解决方案1】:

我在 2016 年遇到了同样的问题 :)
当您使用'server' 模式时,您需要监听'sync' 事件,而不是'reset'

// in a view
this.listenTo(this.collection, 'sync', this.renderPage);

来自骨干文档 (http://backbonejs.org/#Collection-fetch):

当模型数据从服务器返回时,它使用设置为 (智能地)合并获取的模型,除非你通过 {reset: true},在这种情况下,集合将(有效地)重置。

所以默认情况下它不会调用reset(),因此也不会调用'reset' 事件。

我在这个答案中发现了 'sync' 事件: https://stackoverflow.com/a/17053978/1657101

从骨干网 1.0 开始,model.fetch() 会触发“同步”。这就是你应该绑定的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-16
    相关资源
    最近更新 更多