我创建了一个包含对象的模型的自定义对象,当我在ItemView中以this.options.unique的形式拾取该对象时,由于出现错误提示.toJSON,所以我无法运行Uncaught TypeError: this.options.unique.toJSON is not a function。想知道如何解决此问题?

小提琴http://jsfiddle.net/kyllle/73m2ena9/3/

JS

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


var PersonsItemView = Mn.ItemView.extend({
    template: '.js-tmpl',

    templateHelpers: function() {
        return {
            unique: this.options.unique
        }
    },

    initialize: function() {
        console.log(this.options.unique.toJSON());
    }
});


var peopleCollection = new PeopleCollection(peopleArr);

var unqiueList = peopleCollection.filter(function(person) {
    include = true;
    exclude.forEach(function(exl) {
        console.log(exl);
        if (JSON.stringify(exl) == JSON.stringify(person)) {
            include = false;
            return;
        }
    })
    if (include) return person;
});

console.log(unqiueList);

var personsView = new PersonsItemView({
   unique: unqiueList
});


var region = new Backbone.Marionette.Region({
    el: '.js-ctn'
});

region.show(personsView);


更新
我在模板each中添加了一个变量来获取模型并转到toJSON,有人可以建议这种方法是否可以接受吗?

<script type="text/html" class="js-tmpl">
<form action="">
    <% _.each(unique, function(person) { %>
        <% var personDetails = person.toJSON() %>
        <input type="radio"><%= personDetails.name %><br>
    <% }) %>
</form>




更新小提琴http://jsfiddle.net/kyllle/73m2ena9/7/

最佳答案

筛选集合时,它将返回数组,而不是您期望的集合(ref)。因此,您可以使用从集合返回的数组创建集合的新实例。

var unqiueList = peopleCollection.filter(function(person) {
    include = true;
    exclude.forEach(function(exl) {
        console.log(exl);
        if (JSON.stringify(exl) == JSON.stringify(person)) {
            include = false;
            return;
        }
    })
    if (include) return person;
});

unqiueList= new peopleCollection.reset(unqiueList);

var personsView = new PersonsItemView({
   unique: unqiueList
});


FIDDLE LINK

09-17 20:22
查看更多