Ran
Ran

Reputation: 155

Knockout click data-bind not firing

I know it must be super easy for you. But I have been looking for this code for hours and cannot see where I did wrong.

I'm trying to show 2 input when a list item is click with its value. But nothing work. So I tried just to put a simple button with a click event. Yet it still does not fire. Can you please tell me what is wrong with my code?

<!--HTML-->
<input type="button" data-bind="click: $root.onClick">

//JS
//that the basic. the full code in jsfiddle
function Workers(){
        self = this;
        self.onClick = function() {
            alert('2');
        };
    }

    ko.applyBindings(new Workers());

http://jsfiddle.net/cr7cy36m/

Thanks a million! Ran

Upvotes: 0

Views: 2163

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312115

You need to make self a local variable instead of a global by declaring it with var:

function Workers(){
    var self = this;
    self.onClick = function() {
        alert('2');
    };
}

Without the var, self in that function is the same self as you have in the Worker function, so its value gets overwritten with the Worker version.

See http://jsfiddle.net/cr7cy36m/1/

Upvotes: 4

Related Questions