My question pertains to the click binding in Knockout and a specific behavior that I have observed. While there are numerous questions about click bindings on this platform, none seem to address the behavior I am encountering.
I have grasped that in Knockout, click bindings with parameters are executed during page load since Knockout needs a reference to a function. Therefore, when it encounters a function call within a binding, it executes that function expecting a returned function reference to bind to. Consequently, if I were to return another reference to a function, that particular function would be executed upon clicking the element.
So far, everything seems logical and clear.
To test this theory myself, I hastily created the following:
HTML:
<input data-bind="click: selectImportType(1)" type="button" />
JS
var functiontest = function () {
alert('test');
};
viewModel.selectImportType = function (type) {
viewModel.selectedImport(type);
return functiontest;
}
Upon executing this code snippet, I noticed that the 'functiontest' reference is indeed returned to the binding, causing the functiontest function to be called as expected when the element is clicked.
However, here comes my confusion. I discovered that the selectImportType function is also invoked when the element is clicked. First, selectImportType is triggered followed by a call to the functiontest function.
How is this dual invocation possible? The reference resolved during the binding was specifically to the functiontest function!