骨干。渲染/重置过滤后的集合

时间:2014-06-18 19:38:05

标签: javascript backbone.js

我遇到渲染功能问题。该函数将数组作为参数返回集合的新模型。但它只呈现一次。我在点击时运行它,集合本身听“改变”。问题是集合没有获得新项目。

我认为它的重置功能就是问题所在。但我不知道如何以另一种方式做到这一点。基本上我只想删除所有以前的模型并设置新模型。我该怎么做?

谢谢!

filter: function(f) {

    var filter = this.collection.filter(function(o){ 
        var accept = false;                                    
        $(f).each(function(i,val){
            if(_.indexOf(o.get('tags'), val) >-1){
                accept = true;                      
            }
        })
        return accept; 
    });

    this.collection.reset(filter);

    new PeopleView({
        el: this.$('.list'),
        collection: this.collection
    });

},

PeopleView渲染:

PeopleView = Backbone.View.extend({

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

render: function () {
    this.$el.html('');
    this.collection.each(this.renderPerson, this);
    this.listenTo(this.collection,'change',this.render);
},

renderPerson: function (person) {
    this.$el.append(new PersonView({
        tagName: 'li',
        id:'p_'+person.get('id'),
        model: person
    }).el);
},

});

2 个答案:

答案 0 :(得分:0)

我在代码笔上创建了一个更简单的版本,并使其工作(没有视图和过滤条件是硬编码的)但原理似乎相同

主要区别在于它会监听"重置"在我的收藏中看到的事件就是你要求收藏品做的事情。 You can see it here,只需打开控制台即可查看结果

var PeopleModel = Backbone.Model.extend({
});
var PeopleCollection = Backbone.Collection.extend({
    model: PeopleModel
});

var peopleCollection = new PeopleCollection([{
    id: 1,
    name: "jim"
}, {
    id: 2,
    name: "fred"
}]);

//listen for restet
peopleCollection.on("reset", function() {
    console.log("people reset");
    console.log(peopleCollection.models);
});

var filter = peopleCollection.filter(function(o) {
    var accept = false;
    $(['i']).each(function(i, val) {
        if (_.indexOf(o.get('name'), val) > -1) {
            accept = true;
        }
    });
    return accept;
});
console.log("people:",peopleCollection);//this will print that the collection has two models
peopleCollection.reset(filter); //now i have rest with the filter the log will show only one model

答案 1 :(得分:0)

如果你想从集合中删除一组模型,请尝试以下简单的解决方案

http://backbonejs.org/#Collection-remove

that.collection.remove(filter);