Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firing change event when knockout view model property is updated

Here's a jsfiddle to show what the issue is:

http://jsfiddle.net/boblauer/BgvV4/

I'm trying to fire the change event after a text field is updated. Unfortunately, inside the subscribe method, the text box's value hasn't been updated yet, so when I figure the change event, it's fired too soon.

I need to fire the change event because I have 3rd party code that is out of my control that relies on the change event.

Any suggestions?

like image 244
Bob Lauer Avatar asked Jul 26 '12 14:07

Bob Lauer


1 Answers

A simple solution is to wrap your call to $("#text1").change() in a setTimeout with a timeout of 0. That's enough to let knockout do the (synchronous) update to the textbox value before the jquery change handler gets invoked.

I forked your fiddle to demonstrate: http://jsfiddle.net/SuRYa/1//

If this is something you need to do a lot, a better solution is probably to wrap this behavior in a custom binding where the "update" callback of the binding would fire the jquery change event on the updated element.

like image 154
bmode Avatar answered Oct 15 '22 20:10

bmode