Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving element with jQuery inside knockout event

I've been playing about with knockout.js with jQuery, and I'm very new to knockout.js

My code example and code is here : http://jsfiddle.net/Ninjanoel/ADYN6/

Basically, I'm trying to create a lottery numbers input screen as a test of my knowledge, and I'm now trying to validate the input of a textbox, and then apply special effects to the input box if [onBlur], the text box is not valid.

I have a 'LotteryApp', with an observable array of 'Lines', with a normal array of [5] ko observables to serve as my inputs or 'Number Boxes'. I'm using a template to display each 'Line' and a further template inside that to render the 'Boxes'.

What I'd like is to call perhaps a jquery 'colour fade' plugin [red to bg color] on the textbox if the input isn't correct. But in the 'onBlur' function I've created, I cant find anything in any of the arguments passed to the function to help me call something like myTextBox = jQuery(arguments.something), so that I can do something like jQuery(myTextBox).colourFade()

<input type="text" data-bind="value:n, event:{blur: $parent.onBlur }, uniqueName:true, disable: $parent.isLD" class="lotteryNumber" maxlength="2"/>

is the code in my innermost template handling the onBlur.

self.onBlur = function()...

is the function I wish to call on the 'blur' event.

I am aware that if I use a custom binding e.g. ko.bindingHandlers.myBinding then the 'element' is passed directly to the 'update' and 'init' calls, which I can then use to call jQuery(element).colourFade(), but this is more of an exercise in understanding how to access the element using the standard event bindings, because I can imagine I'll be needing it often and dont wish to do EVERYTHING in a custom binding, and also, with only 'init' and 'update' options inside a custom binding (to my knowledge), I dont think those will be enough (e.g. what about on 'keyup'?), and anyway, the custom bindings appear to be based on a ko.observable rather than an event itself.

Summary :

when using data-bind="event : {blur : myMethod}", how do I, inside of myModel.myMethod, grab the html element that created the event.

like image 995
Ninjanoel Avatar asked Mar 19 '12 14:03

Ninjanoel


1 Answers

The jQuery event object is the second argument in the event handler, so:

self.onBlur = function(data, event) {
    console.log(event.target);
}
like image 77
Douglas Avatar answered Nov 17 '22 17:11

Douglas