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.
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.
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 .
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>
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 :-)
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