Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameter using onclick or a click binding with KnockoutJS

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?

like image 833
BlaShadow Avatar asked Apr 06 '12 04:04

BlaShadow


People also ask

What is data bind click?

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.

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.

How do you bind a function in KnockoutJS?

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 .

How do you activate a KnockoutJS model?

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.


Video Answer


2 Answers

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);     }; }(); 
like image 78
Juliano Sales Avatar answered Oct 06 '22 06:10

Juliano Sales


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()); 
like image 40
John Earles Avatar answered Oct 06 '22 05:10

John Earles