I have this function:
function make(place)
{
place.innerHTML = "somthing"
}
I used to do this with plain JavaScript and html:
<button onclick="make(this.parent)">click me</button>
How can I do this using idiomatic knockout.js?
I have this function:
function make(place)
{
place.innerHTML = "somthing"
}
I used to do this with plain JavaScript and html:
<button onclick="make(this.parent)">click me</button>
How can I do this using idiomatic knockout.js?
Use a binding, like in this example:
Knockout's documentation also mentions a much cleaner way of passing extra parameters to functions bound using an
on-click
binding using function.bind like this:If you set up a click binding in Knockout the event is passed as the second parameter. You can use the event to obtain the element that the click occurred on and perform whatever action you want.
Here is a fiddle that demonstrates: http://jsfiddle.net/jearles/xSKyR/
Alternatively, you could create your own custom binding, which will receive the element it is bound to as the first parameter. On init you could attach your own click event handler to do any actions you wish.
http://knockoutjs.com/documentation/custom-bindings.html
HTML
Js
I know this is an old question, but here is my contribution. Instead of all these tricks, you can just simply wrap a function inside another function. Like I have done here:
And here is the fiddle
A generic answer on how to handle
click
events with KnockoutJS...Not a straight up answer to the question as asked, but probably an answer to the question most Googlers landing here have: use the
click
binding from KnockoutJS instead ofonclick
. Like this:**A note about the actual question...*
The actual question has one interesting bit:
Don't do that! Don't modify the DOM like that when using an MVVM framework like KnockoutJS, especially not the piece of the DOM that is your own parent. If you would do this the button would disappear (if you replace your parent's
innerHTML
you yourself will be gone forever ever!).Instead, modify the View Model in your handler instead, and have the View respond. For example: