0
votes

I am new to knockout.js and am having a problem with binding within a foreach section. I am receiving the error:

Uncaught Error: Unable to parse bindings. Message: ReferenceError: hideSearchElements is not defined; Bindings value: click: hideSearchElements

Here is an exert of the html:

 <div id="searchResults" data-bind="visible: searchIsVisible">
  <label id = "lblSearchResults">select a template:</label>   
  <div data-bind="foreach: titles">
    <div data-bind="text: Title"></div>
    <div data-bind="click: hideSearchElements">hide</div>
 </div>   

And an exert from the viewModel:

var viewModel = function () {      
    this.searchIsVisible = ko.observable(true);               

    this.showSearchElements = function () {
       this.searchIsVisible(true);
    };

    this.hideSearchElements = function (
       this.searchIsVisible(false);                    }
    }

 return new viewModel();

I have both showSearchElements and hideSearchElements working fine outside of the foreach block but when inside it, I get the error.

If I add $parent.hideSearchElements I can bind but then get an error saying:

Uncaught TypeError: Object # has no method 'searchIsVisible' .

I have probably have two distinct issues but thought the detail may help :)

I'm keen to understand what's going on here? Can anyone help please?

A link to the relevant page in the documentation would also be very helpful - I'm reading through that now.

Thanks

1

1 Answers

1
votes

You was right when use $parent.hideSearchElements because hideSearchElements function is in a parent context. You got exception because when knockout calls your function this has another context. You have to use closure to store this pointer. Update your view model as follow:

var viewModel = function () {   
    var self = this;   
    self.searchIsVisible = ko.observable(true);               

    self.showSearchElements = function () {
       self.searchIsVisible(true);
    };

    self.hideSearchElements = function (
       self.searchIsVisible(false);                    }
    }