Skip to content
This repository

fill / setField don't work with knockout.js's hasfocus #154

Closed
nh2 opened this Issue June 21, 2012 · 4 comments

2 participants

Niklas Hambüchen Nicolas Perriault
Niklas Hambüchen
nh2 commented June 21, 2012

I'm trying to test an application written using knockout.js with casper.

I have an input text field using the hasfocus binding, which updates an variable whenever the text field is changed.

The problem is that fill and, called by it, setField, don't work on my text field: It is just left blank.

I investigated and found out that when I call

f = $('#myinput')[0]; f.focus(); f.value="myvalue"; f.blur();

knockout resets the text field to what it was before changing the .value as soon as blur() is called.

That makes sense in some way, as knockout's code is (in coffeescript for simplicity):

ko.bindingHandlers["hasfocus"] =
  init: (element, valueAccessor, allBindingsAccessor) ->
    writeValue = ->
      modelValue = valueAccessor()
      valueToWrite = element.ownerDocument.activeElement is element
      ko.jsonExpressionRewriting.writeValueToProperty modelValue, allBindingsAccessor, "hasfocus", valueToWrite, true

    ko.utils.registerEventHandler element, "focus", writeValue
    ko.utils.registerEventHandler element, "focusin", writeValue
    ko.utils.registerEventHandler element, "blur", writeValue
    ko.utils.registerEventHandler element, "focusout", writeValue

  update: (element, valueAccessor) ->
    value = ko.utils.unwrapObservable(valueAccessor())
    (if value then element.focus() else element.blur())
    ko.utils.triggerEvent element, (if value then "focusin" else "focusout")

The problem is that using setField, the change event is not called. If I use this instead:

f = $('#myinput')[0]; f.focus(); f.value="myvalue"; $(f).change(); f.blur();

The value stays.

Therefore the question is: If casperjs wants to simulate what the user does to a website, shouldn't it call $(..).change() (resp. the non-jQuery equivalent) in function setField before calling field.blur();?

Nicolas Perriault
Owner
n1k0 commented June 21, 2012

Do you know how to trigger a change event using the DOM api?

Nicolas Perriault
Owner
n1k0 commented June 21, 2012

Could you please test the fix I've just pushed to a new change-event feature branch? Thanks.

Niklas Hambüchen
nh2 commented June 21, 2012

To answer your first question: Yes (but only since 20 minutes before I commented ;-):

http://jehiah.cz/a/firing-javascript-events-properly

But I see you already did that, I will try the branch.

Nicolas Perriault n1k0 closed this in 29f9b95 June 22, 2012
Niklas Hambüchen
nh2 commented June 22, 2012

Thanks for the fast fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.