Bryan Dellinger
Bryan Dellinger

Reputation: 5294

knockout accessing a parent observable in child function

in knockout given a viewmodel

 function Model() {
     var self = this;
     this.mycollection = ko.observableArray("")
     this.foo = ko.observable("foo");
     ....
  }

in the observable array how do I access the parent?

 function mycollection (bar){
           var self = this;
           this.bar = ko.observable(bar);
           this.myFunction = function() {
              var foo = $parent.foo();
              ...
              }
           }

is it self.$parent.foo? or do I need to pass it in somehow when I call the function?

 <div class="modal-body" data-bind="foreach: selectedFilteredPoCollection">
    ....
     <button type="button" class="btn btn-default" 
                                   data-bind=" click:  myFunction($parent.foo()) </button>

  </div>

Upvotes: 0

Views: 2039

Answers (2)

CrimsonChris
CrimsonChris

Reputation: 4641

bind it to your click function.

<button type="button" data-bind="click: myFunction.bind($parent, $parent.foo)"></button>

Upvotes: 2

dfperry
dfperry

Reputation: 2258

you need to wrap your click handler in a function, like so:

<button type="button" 
        class="btn btn-default" 
        data-bind=" click: 
             function(){ 
                 myFunction($parent.foo());
             }"> </button>

See Note 2 here: http://knockoutjs.com/documentation/click-binding.html

Upvotes: 0

Related Questions