How to pass the current element to a Javascript function in a Knockout.js binding?

So, I'm trying to add a class to an element using Knockout.js based on checking the child checkbox. For this, I am trying to pass this as an argument to my function. Currently, my shortened DOM structure is as follows:

 <tr data-bind="css: { selected: isRowChecked(this) }"> <td><label><input type="checkbox"></label></td> </tr> 

My isRowChecked function is this (I use jQuery to search for input):

 function isRowChecked(elem) { var checkbox = $(elem).find('input[type="checkbox"]'); return checkbox.checked; } 

However, if I console.log elem all I get is a global window object.

It is impossible to use jQuery to completely solve this problem, because the project I'm working on already uses knockout almost exclusively. Any ideas?

+6
source share
1 answer

You must do this by passing the special $ element to the binding context variable. The last variable is discussed here .

$ item

This is an element of the DOM object (for virtual elements it will be a comment of the DOM object) of the current binding. This can be useful if the binding requires access to the attribute of the current element. Example:

<div id="item1" data-bind="text: $element.id"></div>

In your case, it will look like this:

 <tr data-bind="css: { selected: isRowChecked($element) }"> <td><label><input type="checkbox"></label></td> </tr> 
+11
source

Source: https://habr.com/ru/post/978653/


All Articles