Reputation: 6896
On my page I want to track which button the user clicked in an observable:
self.action = ko.observable();
I can write a function setAction
and call it with a parameter on each button click, something like this:
self.setAction = function (action) {
self.action(action);
}
But I'm wondering if there is a way to do it without having to call each time the setAction
function?
Upvotes: 1
Views: 878
Reputation: 1747
You could do it inline:
<button type="button" class="btn" data-bind="click: action.bind($data, 'btn-name')">btn-name</button>
or pass the actual button object
<button type="button" class="btn" data-bind="click: action.bind($data, this)">btn-name</button>
Or if your issue is the fact that you have to write this click event each time, you could add a class to each button and add a event listener to set the action.
<button type="button" class="btn actionBtn">btn-name</button>
$(".actionBtn").click(function(){
var btn = $(this);
viewModel.action(btn);
});
Upvotes: 2