我有一个带有嵌套数组的数组结构。我试图从嵌套数组中删除一个项目,但我得到“删除不是一个函数”的错误。
我在一个简单的jsFiddle - http://jsfiddle.net/rswailes/gts5g/中重新创建了问题,并粘贴了下面的代码。
我设置可观察量的方式可能不正确,但我很难过。
这是我的HTML:
<script id="bookGroupTemplate" type="text/html">
<br/>
<h3><span data-bind="text: group_name"></span></h3>
<table>
<thead>
<tr>
<th>Author</th>
<th>Title</th>
<th>Genre</th>
<th></th>
</tr>
</thead>
<tbody data-bind='template: {name: "bookRowTemplate", foreach: books}'></tbody>
</table>
</script>
<script id="bookRowTemplate" type="text/html">
<tr>
<td data-bind="text: author"></td>
<td data-bind="text: title"></td>
<td data-bind="text: genre"></td>
</tr>
</script>
<h1>Books!</h1>
<div data-bind='template: {name: "bookGroupTemplate", foreach: bookGroups}'></div>
<br/><br/>
<button data-bind="click: function(){viewModel.handleButtonClick(); }">Move One From Now to Later</button>
这是javascript:
var BookGroup = function(group_name, booksToAdd){
var self = this;
this.group_name = ko.observable(group_name);
this.books = ko.observableArray();
_.each(booksToAdd, function(book){
self.books.push(ko.observable(book));
});
}
var Book = function(author, title, genre) {
this.author = ko.observable(author);
this.title = ko.observable(title);
this.genre = ko.observable(genre);
}
var PageViewModel = function() {
var self = this;
this.bookGroups = ko.observableArray();
this.bookToUse = new Book("Robin Hobb", "Golden Fool", "Fantasy");
this.indexAction = function() {
var groups = [];
var booksArray = [];
booksArray.push(this.bookToUse);
booksArray.push(new Book("Patrick R Something", "Name Of The Wind", "Fantasy"));
booksArray.push(new Book("Someone Else", "Game Of Thrones", "Fantasy"));
groups.push(new BookGroup("To Read Now", booksArray));
booksArray = [];
booksArray.push(new Book("Terry Pratchett", "Color of Magic", "Discworld"));
booksArray.push(new Book("Terry Pratchett", "Mort", "Discworld"));
booksArray.push(new Book("Terry Pratchett", "Small Gods", "Discworld"));
groups.push(new BookGroup("To Read Later", booksArray));
this.bookGroups(groups);
};
this.handleButtonClick = function(){
console.log(this.bookGroups()[0].books().length);
this.bookGroups()[0].books().remove(this.bookToUse);
};
};
viewModel = new PageViewModel();
ko.applyBindings(viewModel);
viewModel.indexAction();
为什么删除不符合此处?这是构建模型的正确方法吗?
非常感谢任何建议:)
答案 0 :(得分:1)
您是否在observableArray上尝试remove
而不是在其内容上,换句话说:
this.handleButtonClick = function(){
console.log(this.bookGroups()[0].books().length);
this.bookGroups()[0].books.remove(this.bookToUse);
};
答案 1 :(得分:1)
有2个错误: