Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access $parent or $parents[] in knockout viewmodel click event?

Tags:

I've got a situation where I'd like to notify a grandparent or $parents[1] of a click event that occurs in a sub viewmodel. So basically I'd like to be able to do this

self.$parents[1].actionTaken 

I think this doesn't work because of binding context vs viewModel but I'd like to hear if anyone has an ideas on the correct way to do something like this. Thanks

 self.save = function () {       //do stuff to self first, then        self.$parents[1].actionTaken();  }; 
like image 439
NullReference Avatar asked Aug 09 '13 00:08

NullReference


People also ask

What is $parent in knockout?

$parent. This is the view model object in the parent context, the one immeditely outside the current context. In the root context, this is undefined. Example: <h1 data-bind= "text: name" ></h1>

What is $data in knockout?

The $data variable is a built-in variable used to refer to the current object being bound. In the example this is the one of the elements in the viewModel.

How does KnockoutJS work?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites. The model separates the application's Model (stored data), View (UI) and View Model (JavaScript Representation of model).

What is knockout ViewModel JS?

A ViewModel can be any type of JavaScript variable. In Example 1-3, let's start with a simple JavaScript structure that contains a single property called name .


1 Answers

Or use the bind trick

data-bind="click: $parent.foo.bind($parent)" 

Now when you access your foo function the this keyword will point to the parent context.

foo: function(child) {    this.children.remove(child); } 
like image 168
Anders Avatar answered Sep 22 '22 12:09

Anders