1

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!

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • Is it any better if you change the event from `click` to `change`? – STT Oct 15 '14 at 09:14
  • If changed to `change`, `toggle` is not triggered if I run `$("#show_user").click()`? – Freewind Oct 15 '14 at 09:23
  • `.click` triggers `change` for me, check fiddle: http://jsfiddle.net/bz0he3ep/1/ – STT Oct 15 '14 at 09:31
  • Possible duplicate: http://stackoverflow.com/questions/8423217/jquery-checkbox-checked-state-changed-event – hindmost Oct 15 '14 at 11:42
  • I tried this exact scenario locally, and when I do `event.currentTarget.checked` always matches the checked state of the checkbox. In other words, the code you've presented here works, which suggests that there is some other code involved which you're not sharing that is causing the problem. Is it possible you have another event handler bound to the same `#show_user` element, or to a parent of that element? – machineghost Oct 15 '14 at 17:19
  • In a jasmine test, I need also to call `$("#show_user").change()` after `$("#show_user").prop("checked", true)` to trigger the `change` event. It's working now – Freewind Oct 16 '14 at 05:33

0 Answers0