Last active
October 5, 2017 14:10
-
-
Save absent1706/501f4ab462bf4f9d527e4012353044ac to your computer and use it in GitHub Desktop.
Knockout mapping for filling observableArray with view models from AJAX request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<body> | |
<button data-bind="click: loadProducts">Load Products</button> | |
<ul data-bind="foreach: products"> | |
<li> | |
<span data-bind="text: id"></span> | |
<span data-bind="text: name"></span> | |
</li> | |
</ul> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-debug.js"></script> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script> | |
<script> | |
function Product(data) { | |
ko.mapping.fromJS(data, {}, this); | |
} | |
function VM() { | |
var self = this; | |
self.products = ko.observableArray(); | |
self.loadProducts = function() { | |
data = [ | |
{ | |
"id": 1, | |
"name": "prod1" | |
}, | |
{ | |
"id":2, | |
"name":"prod2" | |
} | |
]; | |
// self.products([]); | |
// data.forEach(function(params){ | |
// self.products.push(new Product(params)); | |
// }) | |
var mapping = {create: function(options) { | |
return new Product(options.data); | |
}}; | |
ko.mapping.fromJS(data, mapping, self.products); | |
}; | |
} | |
vm = new VM(); | |
ko.applyBindings(vm); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment