gpt4 book ai didi

javascript - KnockoutJS - 当 remove 不是函数时如何从 observableArray 中删除对象?

转载 作者:行者123 更新时间:2023-11-30 18:17:59 24 4
gpt4 key购买 nike

我有一个带有嵌套数组的数组结构。我试图从嵌套数组中删除一个项目,但我收到“删除不是函数”的错误。

我在一个简单的 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();

为什么这里不识别remove?这是构建模型的正确方法吗?

非常感谢任何建议:)

最佳答案

有两个错误:

  • 您尝试从 javascript 数组而不是可观察数组调用移除函数。
  • 将 book 对象放入 observableArray 时,不需要用 observable 包装它。

关于javascript - KnockoutJS - 当 remove 不是函数时如何从 observableArray 中删除对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12815135/

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