I am creating a list of links using a knockout binding:
The Javascript and view model looks like this:
$(function () {
var adminViewModel = function()
{
var self = this;
self.leftItems = ko.observable([ { Name: "Item1", Id: 0 }]);
self.getChildren = function (id, list) {
var url ="@Url.Content("~/api/Test/GetChildren/")" + id;
$.getJSON(url, function (data) {
list(data);
});
};
}
var Admin3App = window.Admin3App = window.Admin3App || {};
Admin3App.viewModel = new adminViewModel();
ko.applyBindings(Admin3App.viewModel);
function getLeftChildren(id)
{
Admin3App.viewModel.getChildren(id, Admin3App.viewModel.leftItems);
}
getLeftChildren(0);
}
(EDIT: the init of the ko.observable was missing an Id (even though this did not cause an error, added it)
How this works is the view model will load a bunch of items that has no parent (id 0).
For the sake of simplicity I only included the left version. But the page has a list of items on the left and right so there is a function for each.
The left items is populated to view model left items and displayed as below. But each item is a link and once clicked via javascript will refresh the items based on the parent Id. (Much like browsing a folder viewer in explorer).
But i cannot figure out how to declare the binding in knockout to build up the url. I know this is probably rediculously easy and I am just missing it.
here is the html I have attempted amongst others
<div class="leftView">
<div data-bind="foreach: leftItems">
<a data-bind="text: Name, attr : { href:'javascript:getLeftChildren(' + Id + ')' }"></a><br />
</div>
</div>
(EDIT: missed a single quote, but got the same error anyway)
But I keep getting a binding error
A couple of things:
1) leftItems should ideally be an observableArray
2) The initial object you push into leftItems does not have an Id property
Here is a JSfiddle that corrects a few things and demonstrates loading an initial set of data and then calling again to load different data. I’ve also moved the outside JavaScript call inside the viewModel and switched to using a click handler to pass refresh the data (note that a click binding will automatically send the data item into the event handler as the first parameter, so you have access to the id you need for creating your URL).
http://jsfiddle.net/jearles/xTHFg/