Reputation: 2177
I am using durandal to create a web application. I am using knockout to bind values to page from server. I have an issue in binding knockout observableArray to page and it is a bit complex array.
My observableArray looks like,
In view,
<ul data-bind="foreach: products">
<li><span data-bind='text: product' /></li>
</ul>
No error and not working.
js code.
define(['plugins/http', 'durandal/app', 'knockout'], function (http, app, ko) {
var system = require('durandal/system');
var vm = {
activate: activate,
attached: viewAttached,
products: ko.observableArray([])
};
return vm;
function activate() {
var that = this;
var pdts;
var recs;
var recipeJson = [];
http.get('http://***/Umbraco/Api/Products/GetAllProducts').then(function (response) {
pdts = response;
http.get('http://***/Umbraco/Api/Recipes/GetAllRecipes').then(function (response1) {
recs = response1;
$.each(pdts, function (i, item) {
var json = [];
$.each(recs, function (j, jtem) {
if (item.DocumentTypeId == jtem.BelongstoProduct) {
json.push(jtem);
}
});
jsonitem = {}
jsonitem["product"] = item.ProductName;
jsonitem["recipes"] = json;
recipeJson.push(jsonitem);
});
that.products = recipeJson;
return that.products;
});
});
}
function viewAttached(view) {
$("#accordion > li > div").click(function () {
if (false == $(this).next().is(':visible')) {
$('#accordion ul').slideUp(300);
}
$(this).next().slideToggle(300);
});
}
});
Please help, Thanks.
Upvotes: 0
Views: 1110
Reputation: 37177
When you write
that.products = recipeJson;
you're replacing your observableArray
with a plain array. You should either write
that.products(recipeJson);
instead, or just push each item directly into the observable array instead of going through recipeJson
at all, with that.products.push(jsonItem)
.
Upvotes: 2