Reputation: 1951
Code
function Product(name) {
this.name = ko.observable(name);
}
function ProductViewModel() {
var self = this;
self.products = ko.observableArray();
$.getJSON("/admin/test", function(allData) {
var mappedProducts = $.map(allData, function(item) { return new Product(item.name) });
self.products(mappedProducts);
console.log(self.products);
});
}
ko.applyBindings(new ProductViewModel());
Problem: while allData
and mappedProducts
are properly set (just an array of products with name and some other field), the line console.log(self.products);
is printing an empty array.
I am really confused, i am at first approach with KO but this seems the very same code from the tutorials... im just using products instead of tasks. I'm sure i'm missing something silly.
Upvotes: 0
Views: 900
Reputation: 63719
You should log the thing inside the observable instead of the observable itself:
console.log(self.products());
See this fiddle for a demo with your code in it.
In the question's situation it depends on the browser what will get logged. Granted, Chrome is somewhat confusing:
[]
Seems like an empty array. Internet Explorer 10 makes more sense, outputting:
function c(){if(0<arguments.length)return c.equalityComparer&&c.equalityComparer(d,arguments[0])||(c.K(),d=arguments[0],c.J()),this;a.q.bb(c);return d}
That is: the fact that self.products
is in fact a function (an observable). Firefox is in between, outputting:
c()
Not as helpful as IE10, but not as confusing as Chrome either.
Upvotes: 2
Reputation: 8987
This is for setting the observable :
self.products(mappedProducts)
And this is for getting the value of an observbale or a computed
var mappedProducts = self.products();
Notice the parenthesis.
I hope it helps.
Upvotes: 1