1
votes

Following is how I am adding a function ClickAction in my viewModel

$.getJSON("api/BrowseCategory/Get", function (data) {
    categoryViewModel = ko.mapping.fromJS(data);
    categoryViewModel.clickAction = function () {
            alert('hi');
        }
    ko.applyBindings(categoryViewModel, $('.categories-gallery .frame').get(0));
});

but When I try to call this function .I get the error message "Error: Unable to parse bindings.Message: ReferenceError: clickAction is not defined;"

Here is how I am calling the function.

<section class="categories-gallery">
                        <div class="holder">
                            <div class="frame">
                                <article class="category-spacer"></article>
                                <!-- ko foreach: $data -->
                                <!-- ko foreach: ProductVariants -->
                                <article class="category" data-bind="click: clickAction,attr: { 'data-uuishlist-product-variant': JSON.stringify(ko.mapping.toJS($data)) }, css: { active: (($parentContext.$index() * $parent.ProductVariants().length) + $index()) == 1 }">
     </article>
                                <!-- /ko -->
                                <!-- /ko -->
                            </div>
                        </div>
</section>

I am using knoutoutjs mapping plugin to make viewmodel from json object. so how can I call a function on click?

1

1 Answers

2
votes

Inside of a foreach loop, you are binding against the properties of the current array item. However, you can use the special variables $parent, $parents, and $root to bind against objects from higher levels.

In your case, you should be able to bind against $root.clickAction to jump up to the root view model.

Further reference on the special context variables: http://knockoutjs.com/documentation/binding-context.html