0

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 Answer 1

1

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);                    }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I just this second figured that out: stackoverflow.com/questions/10904070/….

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.