Get data binding element (using KnockoutJS)

goal

Get the element that called the function.

Problem

See my code:

<span data-bind="ifnot: ProductLayout.existsAtSummary()"> <button class="btn btn-success btn-small add" title="Adicionar à lista de comparação"> <i class="icon-plus"></i> </button> </span> <span data-bind="if: ProductLayout.existsAtSummary()"> <button class="btn btn-danger btn-small remove" title="Remover da lista de comparação"> <i class="icon-remove"></i> </button> </span> 

As you can see, I run the existsAtSummary() function when if and ifnot are true or false.

But these buttons are inside the foreach, and I need their elements to work, and I don't know how to do this.

My JS:

 function ProductLayoutViewModel() { var self = this; self.existsAtList = function () { return true; }; } ko.applyBindings(new ProductLayoutViewModel()); 

Name my code here on JSFiddle .

My idea

I thought about it:

 self.existsAtList = function (element) { console.log(element); // returns me 'undefined' return true; }; 

But, as I said, the console returns me "undefined".

Any ideas?

More details

If necessary, I can use jQuery.

+6
source share
1 answer

I think you are looking for $element :

 <span data-bind="ifnot: existsAtList($element)"> <button class="btn btn-success btn-small add" title="Adicionar à lista de comparação"> <i class="icon-plus"></i> </button> </span> <span data-bind="if: existsAtList($element)"> <button class="btn btn-success btn-small add" title="Eliminar de lista de comparação"> <i class="icon-minus"></i> </button> </span> 

and

 function ProductLayoutViewModel() { var self = this; self.existsAtList = function (element) { console.log(element); return true; }; } ko.applyBindings(new ProductLayoutViewModel()); 

See http://jsfiddle.net/rSD7q/1/

+2
source

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


All Articles