This question build up on KnockoutJS: Tracking menu clicks and KnockoutJS: Event object. I have re-factored the code a bit to seperate the viewModel and the UI logic. What I'm trying to do now is convert the "Children" object array of each "Menu" object into an observableArray so I can add/remove a menu's children to change my UI.
Here is my simplified code:
var viewModel = {};
var viewContext = {
initialize: function (data) {
viewModel = data;
//for (var i = 0; i < viewModel.Panels.length; i++) {
viewContext.observe(viewModel.Panels[0].Menu);
//}
viewModel.menuActive = ko.observable(false);
viewModel.currentMenu = ko.observable(0);
viewModel.currentNode = ko.observable({});
viewModel.currentList = ko.observableArray([])
},
observe: function (data) {
for (var i = 0; i < data.Children.length; i++) {
viewContext.observe(data.Children[i]);
}
data.Children = ko.observableArray(data.Children);
},
nodeClicked: function (event) {
var target = $(event.target)
var data = target.tmplItem().data
viewContext.getData(data, function (response) {
viewModel.currentList(response.d);
data.Children(response.d);
});
viewModel.currentNode(data);
},
getData: function (data, onSuccess) {
$.ajax({
url: 'console.asmx/' + data.Method,
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
data: ko.utils.stringifyJson(data),
dataType: "json",
success: onSuccess,
error: function () {
viewModel.currentList([]);
}
});
}
};
$(function () {
$.ajax({
url: 'console.asmx/Initialize',
type: "POST",
cache: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: function (data) {
viewContext.initialize(data.d);
ko.applyBindings(viewModel);
}
});
});
When the page is initially rendered (using the templates in the referenced questions), everything is fine. However, when I click on a menu which is fires the "nodeClicked" event, I get an error on the line data.Children(response.d); that says "Uncaught ReferenceError: Children is not defined".
My guess is that the line data.Children = ko.observableArray(data.Children); is not converting my array properly into an observableArray.
Any ideas will be greatly appreciated.
data.Childrendefined whenko.observableArray(data.Children)is called?