Get the element that triggered a function.
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 am triggering existsAtSummary()
function when if
and ifnot
is true or false.
But these buttons are inside of a foreach and I need to get their elements to work with and I do not know how.
My JS:
function ProductLayoutViewModel() {
var self = this;
self.existsAtList = function () {
return true;
};
}
ko.applyBindings(new ProductLayoutViewModel());
Se my code here, on JSFiddle.
I was thinking about this:
self.existsAtList = function (element) {
console.log(element); // returns me 'undefined'
return true;
};
But as I have commented, the console returns me "undefined".
Any ideas?
If necessary, I can use jQuery.
To read the observable's current value, just call the observable with no parameters. In this example, myViewModel. personName() will return 'Bob' , and myViewModel. personAge() will return 123 .
Knockout's declarative binding system provides a concise and powerful way to link data to the UI. It's generally easy and obvious to bind to simple data properties or to use a single binding.
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.
Binding Values The binding value can be a single value, literal, a variable or can be a JavaScript expression.
I think what you're looking for is $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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With