【问题标题】:Cannot call method 'push' of undefined无法调用未定义的方法“推送”
【发布时间】:2013-06-15 14:22:07
【问题描述】:

我在小提琴中工作得很好(我现在找不到),但是当我将它移到 VS2012 时,我收到错误“无法调用未定义的方法‘push’。

在下面的代码中,createItemDiv() 函数运行良好并创建了 UI 元素。在那之前的那一行,调用 this.visibleItem.push() 的 showItem() 引发了错误。我最初在小提琴中遇到了这个问题,并添加了“this”来修复它。如果我现在删除“this”,我会得到“visibleItem is not defined”。

viewmodel.js

var dummyResults = [
    { //sample data is here }
]
var dummyItems = [
]

function VisibleItem(data) {
    var self = this;
    this.name = ko.observable(data.name);
    this.type = ko.observable(data.type);
    this.description = ko.observable("");
}

function SearchResult(data) {
    var self = this;
    this.name = ko.observable(data.name);
    this.type = ko.observable(data.type);
}

var viewModel = {
    searchResult: ko.observableArray(ko.utils.arrayMap(dummyResults, function (item) {
        return new SearchResult(item);
    })),
    visibleItem: ko.observableArray(ko.utils.arrayMap(dummyItems, function (item) {
        return new VisibleItem(item);
    })),
    showItem: function (item) {
        this.visibleItem.push(item);
    }
};


ko.applyBindings(viewModel);

site.js

$(document).on('click', '.result', function () {
    var item = ko.dataFor(this);
    viewModel.showItem(item);     //add item to "visibleItems" viewmodel for management
    createItemDiv(item);          //ui function to show item on screen
});

【问题讨论】:

    标签: mvvm knockout.js


    【解决方案1】:

    试试这个:

    var viewModel = function() {
            var self = this;
            self.searchResult = ko.observableArray(ko.utils.arrayMap(dummyResults, function (item) {
                return new SearchResult(item);
            })),
            self.visibleItem = ko.observableArray(ko.utils.arrayMap(dummyItems, function (item) {
                return new VisibleItem(item);
            })),
            self.showItem = function (item) {
                self.visibleItem.push(item);
            }
        };
    

    【讨论】:

    • 未捕获的错误:无法解析绑定。消息:ReferenceError:searchResult 未定义;绑定值:foreach:searchResult
    【解决方案2】:

    我刚刚意识到我的 html 中有一个旧的绑定仍然......将投票关闭。

    【讨论】:

    • 那是你的问题,你可以删除它,但不要只是提交你的解决方案,只是警告人们不要像你那样做
    • 如果其他人回答了,则不能删除。
    猜你喜欢
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多