0

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.

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.