I have created two JSFiddle Examples for Mapping data with knockout.js.
(1) http://jsfiddle.net/9nn2qpp8/ without the ko.mapping plugin
var ViewModel = function() {
var self = this;
this.entries = [
{ name: "one", type: "file" },
{ name: "two", type: "folder" },
{ name: "three", type: "file" }
];
};
ko.applyBindings(new ViewModel());
(2) http://jsfiddle.net/q49vfy6q/ using ko.mapping
var data = {entries: [
{ name: "one", type: "file" },
{ name: "two", type: "folder" },
{ name: "three", type: "file" }
]};
var viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
Why is (2) not working in the same way as (1) regarding the evaluation of the if binding?
The mapping plugin is automatically wrapping everything as observables - you need to treat them as such in the if
binding:
<!-- ko if: type() !== "file" -->
rather than:
<!-- ko if: type !== "file" -->
Because when you use the mapping, you convert each of the properties into an observable.
Every observable property is a function and so you need to execute the function to return the value inside.
See it working here: http://jsfiddle.net/q49vfy6q/1/
<table> <tbody data-bind="foreach: entries()"> <tr> <td> <!-- ko if: type() === "file" -->
You don't actually need to use mapping
at all. You can pass data
straight into applyBindings()
:
var data = {entries: [
{ name: "one", type: "file" },
{ name: "two", type: "folder" },
{ name: "three", type: "file" }
]};
ko.applyBindings(data);
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.