Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I 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 whether a child checkbox is checked or not. To do so, I'm trying to pass this as an argument to my function. Currently, my abridged DOM structure is the following:

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

An my isRowChecked function is this (I'm using jQuery to locate the input):

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

Yet, if I console.log elem all I get is the global window object.

It is not feasible to use jQuery to solve this problem completely as the project I am working in is already using knockout nearly exclusively. Any ideas?

like image 393
marked-down Avatar asked Nov 25 '14 02:11

marked-down


People also ask

How do you bind a function in KnockoutJS?

The function you want to bind to the element's click event. You can reference any JavaScript function - it doesn't have to be a function on your view model. You can reference a function on any object by writing click: someObject. someFunction .

How do I assign a value to Knockout observable?

To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.

What is two way data binding in KnockoutJS?

KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.

Which function is used to activate KnockoutJS?

To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.


1 Answers

You should be able to accomplish this by passing the special binding context variable $element. It's the last variable discussed here.

$element

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

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

In your case, that would look like this:

<tr data-bind="css: { selected: isRowChecked($element) }">
    <td><label><input type="checkbox"></label></td>
</tr>
like image 133
Josh Avatar answered Oct 18 '22 19:10

Josh