我有一个带有嵌套数组的数组结构。我正在尝试从嵌套数组中删除一个项目,但出现“删除不是函数”错误。

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


为什么在这里无法识别删除?这是构建模型的正确方法吗?

非常感谢您的任何建议:)

最佳答案

有2个错误:


您尝试调用删除功能表单javascript数组而不是可观察数组。
将书对象放到observableArray时,不需要用observable包装书对象。

10-07 19:42
查看更多