gpt4 book ai didi

javascript - 未捕获的类型错误 : Object function () has no method items

转载 作者:行者123 更新时间:2023-12-02 18:07:49 25 4
gpt4 key购买 nike

我正在将 json 数据绑定(bind)到 ul 标记中。它表明发生了错误。代码如下:

<div id="newdiv" data-bind="visible: selectedSection() === 'ulClass', stopBinding: true ">
<ul id="ulClass" data-bind="template: { name: 'templatesSample', foreach: items}">
<script id="templatesSample" type="text/html">
<li><span data - bind = "text:name" > </span>
</li>
</script>
</ul>
</div>

View 模型

function names(firstnames) {
this.name = ko.observable(firstnames);
}

var mappedData;
var viewmodel;

$(document).ready(function () {
ko.bindingHandlers.stopBinding = {
init: function () {
return {
controlsDescendantBindings: true
};
}
};
ko.virtualElements.allowedBindings.stopBinding = true;

viewmodel = function () {
items: ko.observableArray([]);
};


var namesOfPeople = '[{"Firstnames":"john"},{"Firstnames":"peter"},{"Firstnames":"mary"}]';
var dataFromServer = ko.utils.parseJson(namesOfPeople);
mappedData = ko.utils.arrayMap(dataFromServer, function (item) {
return new names(item.Firstnames);
});

viewmodel.items(mappedData);

ko.applyBindings(viewmodel, document.getElementById("ulClass"));
});

它在控制台中显示以下错误:

Uncaught TypeError: Object function ()
{
items:ko.observableArray([]);

} has no method 'items'

如何解决该问题?请提出解决方案。

谢谢

最佳答案

您需要决定是将虚拟机初始化为对象还是使用构造函数。

这是两者的组合,我认为在语法上大多是无效的:):

viewmodel = function()
{
items:ko.observableArray([]);
};

所以要么这样做:

viewmodel = {
items:ko.observableArray([]);
};

或者这个:

var VM=function() {
this.items = ko.observableArray([]);
};

var viewModel = new VM();

关于javascript - 未捕获的类型错误 : Object function () has no method items,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19950684/

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