jQuery.each() for single objects
While refiningĀ jQuery.crossselect.js recently I was briefly faced with a problem which often rears its ugly head, though this time I found a solution.
Consider a function alters_item(), which can be applied to certain DOM elements. Further, consider that it can be triggered in two distinct ways:
- By a click (or other event) on the item to be altered, so the DOM element is the context and can be accessed via the pseudo-variable this
- Just applied like a normal javascript function, which means the DOM element needs to be passed in as a parameter, i.e. you need to call the function using alters_item(element)
So to have a function usable in both circumstances I would write some conditionals at the start which check if an argument has been passed, if it hasn’t then set var element = this, etc…
But there is another way.
For the second case instead of
alters_item(element)
we can write
$(element).each(alters_item)
because jQuery.each works even on jQueries that return only one object.
Doing this is a bit of a trade off – the second line of code I bet takes measurably longer to execute, but it does mean my functions get to be simpler, so it’s my weapon of choice at the moment.
But it does make me think that jQuery should have a call() method, that runs a function on an object, but also setting the object as the context.
Incidentally, if anyone knows of a better way of dealng with this isue than the one I’ve found, please let me know.
Related posts:
- It’s all about contextOne big selling point of jQuery – so everyone says...
- My jQuery plugin writing tipsI’ve now written , and have a pretty good idea...
- In defence of jQuery browser detectionI read somewhere the other week that jQuery is deprecating...
- jQuery listSplitter pluginA very short post to announce my thirdĀ jQuery plugin:...
- crossSelect jQuery pluginI thought I should write a short post to say...