Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help understanding jQuery button enable/disable code

I grabbed this code form JCarousel and just trying to understand these lines below. I'm new to jQuery and not that great at JavaScript so I am not sure what is jQuery and which is JavaScript below

this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
this.buttonPrev[p ? 'bind' : 'unbind'](this.options.buttonPrevEvent, this.funcPrev)[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);

It's setting some of the css to set state and either enabling or disabling the button that is in a but I want to modify this once I really understand it. I just can't make out exactly what it's doing 100%.

Trying to understand things such as [n ? 'bind' : 'unbind'] and just the chaining here also. There's a lot going on in those 4 lines.

The code comes from this plug-in: http://sorgalla.com/projects/jcarousel/

like image 567
PositiveGuy Avatar asked Aug 14 '26 04:08

PositiveGuy


1 Answers

The first part to understand is symbol resolution. Javacript supports both dot-notation and bracket-notation.

Consider opening a new window.

window.open()

This is dot-notation in action. you're telling the interpreter that "open" can be found on "window". But there's another way to do this

window['open']()

Same thing, but with bracket notation. Instead of using the symbol name directly, we're using a string literal instead. What this means is that by using bracket-notation for symbol resolution, we can do it in a dynamic way, since we can choose or build strings on the fly, which is exactly what this snippet does.

this.buttonNext[n ? 'bind' : 'unbind'](...);

Is analagous to

if ( n )
{
   this.buttonNext.bind(...);
} else {
   this.buttonNext.unbind(...);
}

If you don't recognize the ?: syntax, that's the conditional operator, or conditional expression

[expression] ? [valueIfTrue] : [valueIfFalse]

This is extremely often erroneously called the "ternary operator", when in fact it just a ternary operator (an operator with three operands). The reason for this is because in javascript (and most languages) is the only ternary operator, so that description usually flies.

Does that help? is there anything else you need cleared up?

like image 129
Peter Bailey Avatar answered Aug 15 '26 18:08

Peter Bailey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!