Guilherme Oderdenge
Guilherme Oderdenge

Reputation: 5001

Get element of data binding (with KnockoutJS)

The Goal

Get the element that triggered a function.

The 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 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.

My Idea

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?

Details

If necessary, I can use jQuery.

Upvotes: 7

Views: 2562

Answers (1)

sroes
sroes

Reputation: 15053

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/

Upvotes: 3

Related Questions