Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

knockoutjs - bindings with parameters triggered on load

Tags:

knockout.js

I've been doing a lot of knockoutjs lately, and I came across a strange occurence.

As you can see in this fiddle http://jsfiddle.net/hqXjv/ when you set up a binding to click: testMethod then the action fires when the button is clicked.

As you can see in this fiddle http://jsfiddle.net/kxTzM/ when you setup the binding to click: testMethod('hi') the action fires both when the button is clicked and on page load (I'm guessing on applyBindings)

Having a parameter isn't necessary to reproduce the problem, if you change the binding to click: testMethod() in the first fiddle, you see that it is triggered on page load.

While, yes, I could add another attribute to the element and attempt to use that as a parameter, my question is, is there a way to pass parameters to knockoutjs bindings without triggering them onload. If this is a bug, so be it, however I just want to know a way to avoid it.

like image 997
deltree Avatar asked Mar 27 '12 14:03

deltree


People also ask

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.

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 .


2 Answers

I think "Note 2" on this knockout page explains it all:

http://knockoutjs.com/documentation/click-binding.html

You can avoid the problem by either using:

Anonymous functions:

<button data-bind="click: function(data, event) { myFunction(data, event, 'param1', 'param2') }">Click me</button> 

... or ...

The bind method:

<button data-bind="click: myFunction.bind($data, 'param1', 'param2')">Click me</button> 
like image 56
Mark Robinson Avatar answered Sep 17 '22 17:09

Mark Robinson


The following executed the click function on load

click: clickSpan() 

removing the brackets as below, the function was not executed onload

click: clickSpan 

(this is explained in note 2 above but it was in cryptic form :-)

like image 40
atreeon Avatar answered Sep 18 '22 17:09

atreeon