I'm probably about a 7 or 8 on proficiency with jQuery (on a scale of 1-10), so I'm not sure if this even makes sense, but I'd like to know if anyone knows of a jQuery function or possibly a plugin which allows a branch of jQuery to only be executed if a given condition is true. Otherwise, I'd love to hear if someone thinks the concept is flawed in some way (EDIT and how it is flawed)
While one could control attachment of various events using normal JavaScript syntax similar to this:
var desiredElement = $('.parent') // find the parent element
.hover(overFunction,offFunction) // attach an event while I've got the parent in 'scope'
.find('.child-element'); // then find and return the child
if (booleanVar1) { // if one condition
desiredElement.click(clickFunction1); // attach one event
} else if (booleanVar2) { // or if a different condition
desiredElement.click(clickFunction2); // attach a different event
} else { // otherwise
desiredElement.click(clickFunction3); // attach a default event
}
$('.parent').find('.other-child') // (or $('.parent .other-child')
.css(SomePredefinedCssMapping)
.hide()
//...
I was wondering if there is a way to do it all in jQuery or if there is a good reason not to... something perhaps like this:
$('.parent') // find the parent element
.hover({overFunction,offFunction}) // attach an event while I've got the parent in 'scope'
.find('.child-element') // then find the child
.when(booleanVar1) // if one condition
.click(clickFunction1) // attach one event
.orWhen(booleanVar2) // or if a different condition
.click(clickFunction2) // attach a different event
.orElse() // otherwise
.click(clickFunction3) // attach a default event
.end()
.end()
.find('.other-child')
.css(SomePredefinedCssMapping)
//...
Note: I think this is syntactically correct, assuming the booleans and functions are defined appropriately, but I'm pretty sure I've gotten the intent across pretty clearly
the proposed jQuery seems a little neater to me (??) agree/disagree? - so here are my questions:
- Is there some part of native jQuery that basically already does this?
- Is there an extension already out there that allows this type of thing?
- Is it harder to do than I am thinking? (I'd think something like keeping the current element set if the condition is true, pushing an empty element set if condition is false, then popping the element set back out for each
or
condition would do it, just like theend()
method pops back the previous set after afind()
call) - Is there something that makes it significantly less efficient?
EDIT
The question asks how to do this with method chaining or why it would be unadvisable (specifics preferred). While it doesn't ask for alternatives, such alternatives might be necessary to explain problems with a jQuery chaining approach. Also, since the example above immediately evaluates the booleans, any other solution should do the same.