We have a backbone program which will listen on a checkbox. When user clicks on the checkbox, it will trigger a function, but the problem is that the event.currentTarget.checked
is not correct.
Say, there is a template contains a checkbox:
<input type="checkbox" id="show_user" />
It binds to a backbone view, and have such events:
events: {
"click #show_user": "toggle"
},
toggle: function(event) {
this.model.set("show_user", event.currentTarget.checked);
}
So if I clicked the checkbox to select it, I hope event.currentTarget.checked
is true
. But when we run karma test on Chrome(with debugger), we clearly see that it is false
!
If we keep running the debugger line by line, it will be true
after a while.
Why it has such behavior? Is there any other stable way to get the checked
status of a checkbox?
Update:
I think I'm missing some important information. When I say click
on the checkbox, I mean in the jasmine test, I write:
$("#show_user").click()
In this case, the event
parameter in the method toggle
is too early received that the state of the checkbox itself has not been changed yet. If I put it in a setTimeout
with very short time, say:
toggle: function(event) {
setTimeout(function() {
this.model.set("show_user", event.currentTarget.checked);
}, 1);
}
The event.currentTarget.checked
will be correct.
Now I changed it to change
:
events: {
"change #show_user": "toggle"
}
And in my test, I won't use .click()
, instead, I write:
var checkbox = $("#show_user");
checkbox.prop("checked", !checkbox.prop("checked"));
checkbox.change();
to change the state of the checkbox and trigger a change
event. Now it's working well!