I'm trying to use a computed observable to create a custom div ID (eg branch3). However, anytime I attempt to bind the computed I get the "unable to parse bindings" error. I'm sure I could just go about doing this a different way, but I just don't understand why I can't use a computed here. I'm pretty sure I've seen it done.
Here is the jsfiddle I've been working on.
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);
}
And the 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>
You need to convert your raw JavaScript array into an array of Branch
es. One way to do this is to use ko.utils.arrayMap
to iterate over each item in the list and create a new Branch
:
var BranchViewModel = function() {
var self = this;
//create knockout array
self.branchArrayKO = ko.observableArray(ko.utils.arrayMap(branchList, function(branch) {
return new Branch(branch);
}));
}
Updated example: http://jsfiddle.net/hawMW/2/
Another alternative that might be useful is the knockout mapping plugin , which you can use to automate all or part of the mapping process.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.