gpt4 book ai didi

javascript - 如何在 Marionette ItemView 中更新的集合中的对象上运行 toJSON?

转载 作者:行者123 更新时间:2023-12-03 08:26:03 25 4
gpt4 key购买 nike

我创建了一个包含集合中模型的自定义对象,当我在 ItemView 中将此对象作为 this.options.unique 选取时,我无法运行 .toJSON 因为我收到一条错误消息 Uncaught TypeError: this.options.unique.toJSON is not a function。想知道如何解决这个问题?

fiddle 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>

更新了 fiddle 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

关于javascript - 如何在 Marionette ItemView 中更新的集合中的对象上运行 toJSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33543359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com