Neir0
Neir0

Reputation: 13367

How to pass current element to function bound to click event?

Here is code example:

<table>
    <tr data-bind='template: { name: "GridColumnTable", foreach: columns }' ></tr>
</table>    

<script type="text/html" id="GridColumnTable">       
    <td>
        <span data-bind="text:name, click:function(event){ alert('blabla') }">
          none 
        </span>      
    </td>
</script>

And this is the Javascript code:

var viewModel = {
    columns: new ko.observableArray(),
    changeColumnName: function(column)
    {
        column.name('asdas');
    }
}

viewModel.columns.push({       
    name: new ko.observable('column1')
});

    viewModel.columns.push({       
    name: new ko.observable('column2') 
});

    viewModel.columns.push({       
    name: new ko.observable('column3') 
});

    viewModel.columns.push({       
    name: new ko.observable('column4')
});       


ko.applyBindings(viewModel);

See also this JSFiddle.

I want to change column name when a user clicks on it. But I don't know how to pass current element to my changeColumnName function. Any ideas?

Upvotes: 1

Views: 172

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

Inside of a jQuery template the variable $data refers to the data that the template is binding against. So, you would want to call: viewModel.changeColumnName($data)

Upvotes: 2

Related Questions