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?
Click binding is one of the simplest binding and is used to invoke a JavaScript function associated with a DOM element based on a click. This binding works like an event handler. This is most commonly used with elements such as button, input, and a, but actually works with any visible DOM element.
KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.
The function you want to bind to the element's click event. You can reference any JavaScript function - it doesn't have to be a function on your view model. You can reference a function on any object by writing click: someObject. someFunction .
To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.
Use a binding, like in this example:
<a href="#new-search" data-bind="click:SearchManager.bind($data,'1')"> Search Manager </a>
var ViewModelStructure = function () { var self = this; this.SearchManager = function (search) { console.log(search); }; }();
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
<div> <button data-bind="click: clickMe">Click Me!</button> </div>
Js
var ViewModel = function() { var self = this; self.clickMe = function(data,event) { var target = event.target || event.srcElement; if (target.nodeType == 3) // defeat Safari bug target = target.parentNode; target.parentNode.innerHTML = "something"; } } ko.applyBindings(new ViewModel());
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