gpt4 book ai didi

javascript - knockout - 绑定(bind)从模型计算

转载 作者:行者123 更新时间:2023-11-29 14:58:33 24 4
gpt4 key购买 nike

我正在尝试使用计算的可观察对象来创建自定义 div ID(例如 branch3)。但是,每当我尝试绑定(bind)计算时,我都会收到“无法解析绑定(bind)”错误。我确定我可以用不同的方式来做这件事,但我只是不明白为什么我不能在这里使用计算。我很确定我已经看到它完成了。

这是我一直在研究的 jsfiddle。

FIDDLE

var branchList   =[{"Id":1,"Latitude":40.2444400000,"Longitude":-111.6608300000,"StreetAddress":"1525 W 820 N","BranchName":"GPS","City":"Cityplacwe","State":"UT","Zip":"84601"},{"Id":2,"Latitude":40.2455550000,"Longitude":-111.6616100000,"StreetAddress":"123 N Center","BranchName":"GPS Branch 2","City":"Lehi","State":"UT","Zip":"84043"}];

//myMarkers = new Array();

var Branch = function (data) {
var self = this;
self.Id = ko.observable(data.Id);
self.Latitude = ko.observable(data.Latitude);
self.Longitude = ko.observable(data.Id);
self.BranchName = ko.observable(data.BranchName);
self.StreetAddress = ko.observable(data.StreetAddress);
self.City = ko.observable(data.City);
self.State = ko.observable(data.State);
self.Zip = ko.observable(data.Zip);
this.DivId = ko.computed(function () {
return self.Id();
});
//self.DivId = ko.computed({
// //Reading from object to field
// read: function () {
// return "branch" + self.Id();
// },
// //writing from field to object
// write: function (value) {

// }
//});

}

var BranchViewModel = function () {
var self = this;

//create knockout array
self.branchArrayKO = ko.observableArray(branchList);
}

和 HTML

<div data-bind="foreach: branchArrayKO">


<div data-bind="attr: {'id': DivId}">
<p></p>
<h2></h2>
<ul>
<li data-bind="text: Id"></li>
<li data-bind="text: BranchName"></li>
<li data-bind="text: StreetAddress"></li>
</ul>
</div>

</div>

最佳答案

您需要将原始 JavaScript 数组转换为 Branch 数组。一种方法是使用 ko.utils.arrayMap 遍历列表中的每个项目并创建一个新的 Branch:

var BranchViewModel = function() {
var self = this;

//create knockout array
self.branchArrayKO = ko.observableArray(ko.utils.arrayMap(branchList, function(branch) {
return new Branch(branch);
}));
}

更新示例: http://jsfiddle.net/hawMW/2/

另一个可能有用的替代方法是 knockout mapping plugin ,您可以使用它来自动执行全部或部分映射过程。

关于javascript - knockout - 绑定(bind)从模型计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14015029/

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