Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass object from an array when clicked in knockout.js

Tags:

knockout.js

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}
like image 646
Slee Avatar asked Mar 04 '26 10:03

Slee


1 Answers

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());
            };
like image 150
RP Niemeyer Avatar answered Mar 07 '26 05:03

RP Niemeyer