Skip to content Skip to sidebar Skip to footer

Referencing An Object With Through Methods, Events, And Whatnot

Set-Up I'm trying to make an object based validation code for my site where you can define an input as an object and attach properties to it kinda like this function input(id,isReq

Solution 1:

Have a look at .bind():

firstName.getElement().onblur = validate.bind(firstName);

This will make this inside the validate function refer to firstName (so it is not passed as parameter).

It is not supported by all browsers (it is part of ECMAScript5) but the link shows a custom implementation.

Alternatively, you could create a new function which generates the anonymous function for you:

firstName.getElement().onblur = get_validator(firstName);

where get_validator is:

function get_validator(obj) {
   return function() {
       validate(obj);
   }
}

Or you could do the same but as a method of the input object, so that one only has to do:

firstName.getElement().onblur = firstName.getValidator();

Post a Comment for "Referencing An Object With Through Methods, Events, And Whatnot"