【问题标题】:Backbone, after chaging url in my collection, fetch is looping.骨干网,在我的收藏中更改 url 后,fetch 正在循环。
【发布时间】:2015-01-04 00:41:21
【问题描述】:

我对 Backbone 很陌生,我正在为 Backbone.Collection 苦苦挣扎:
我有一份不同类别的产品清单(鞋子、衬衫、裤子……)。这个想法是当用户点击一个类别时,我正在更新我的集合中的 URL(例如:datas/shoes.json 变为 datas/shirts.json)并执行一个 collection.fetch() 以呈现我的新列表。

它确实有效,但我不知道为什么它不断触发“添加”、“删除”事件。这是我的代码,如果你看到奇怪的东西,请告诉我:

define([ 
    "backbone",
],

function(Backbone) 
{
    var ProductsView = Backbone.View.extend({

        el: "#products",

        initialize:function(){

            _.bindAll(this,"addItem","removeAll");
            this.populate();
        }, 

        populate:function(){

            this.collection = new ProductCollection();    
            this.listenTo(this.collection, 'add', this.addItem);
            this.listenTo(this.collection, 'remove', this.removeAll);    
            this.collection.fetch();
        },

        addItem(todo){

            var view = new ProductItemView({model: todo});
            this.$el.append(view.render().el);
        },

        removeAll:function(){

            this.$el.children().remove();
            this.collection.url = "datas/shoes.json";
            this.collection.fetch();
        },
    });

    return ProductsView;
});

这是我的收藏

define([ 
    "backbone",
    "models/modules/products/ProductModel"
], 

function(Backbone, ProductModel) 
{
    var ProductsCollection = Backbone.Collection.extend({

        model : ProductModel,
        url : "datas/shirts.json",

        parse: function(response){
            return response.products;
        },
    });

    return ProductsCollection;
});

感谢您的帮助伙计们!!
如果不清楚,请告诉我,我会尽力澄清。

【问题讨论】:

  • 您将在获取后为不在集合中的每个元素获取一个删除事件,但您已将删除事件绑定到removeAll,这将执行另一次获取。这可能是导致事件不断发生的原因。

标签: loops backbone.js collections fetch


【解决方案1】:

为了后退一步,放弃,上床睡觉,绝对是有帮助的。 所以我阅读了文档并找到了 reset 方法:

remove:function(todo){
    this.$el.children().remove();
    this.collection.reset();
    this.collection.url = "datas/shoes.json";
    this.collection.fetch();
},

【讨论】:

    猜你喜欢
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 2012-09-14
    相关资源
    最近更新 更多