I am new to knockout.js and I am missing something simple here I am sure. I have a list of objects in a list and I simply want to select one of them and get a property from it to load some more data.
JS:
function category(data) {
this.categoryName = ko.observable(data.CategoryName);
this.categoryID = ko.observable(data.CategoryID);
}
function CatalogViewModel() {
//Data
var self = this;
self.categories = ko.observableArray([]);
self.chosenCategoryID = ko.observable();
//Behaviours
self.gotoCategory= function (category) {
self.chosenCategoryID(category.categoryID);
alert(category.categoryID);
};
$.getJSON("/api/catalog", function (allData) {
var mapped = $.map(allData, function (item) { return new category(item) });
self.categories(mapped);
});
}
ko.applyBindings(new CatalogViewModel());
Here is my HTML:
<ul data-bind="foreach: categories">
<li>
<a data-bind="click: $parent.gotoCategory"><label data-bind="text: $data.categoryName"></label></a>
</li>
</ul>
The items list perfectly but then when I click and item, I am hoping to get my categoryID but I get a bunch of javascript instead which looks like a function trying to evaluate and argument.
What am I missing here?
EDIT - HERE IS WHAT I GET IN MY ALERT:
function c(){if(0<arguments.length){if(!c.equalityComparer||!c.equalityComparer(d,arguments[0]))c.I(),d=arguments[0],c.H();return this}a.U.La(c);return d}function c(){if(0<arguments.length){if(!c.equalityComparer||!c.equalityComparer(d,arguments[0]))c.I(),d=arguments[0],c.H();return this}a.U.La(c);return d}
It appears that your categoryID is an observable. To access the value of an observable, you need to call it as a function with no arguments.
So, your gotoCategory should look more like:
self.gotoCategory= function (category) {
self.chosenCategoryID(category.categoryID());
alert(category.categoryID());
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With