PDA

View Full Version : Adding setClass method to Ext.Element



e12win
30 Sep 2009, 7:05 PM
I've created a setClass method on Ext.Element with the following code:



Ext.Element.prototype.setClass = function(cls,add_class){
add_class ? this.addClass(cls) : this.removeClass(cls)
}


There are few situations when Ext.Element.toggleClass is the best choice. In fact, just willy nilly toggling anything is risky because you're assuming that whatever the current state, you want it to be the opposite. That's messy in most cases.

Then there's addClass and removeClass, but those are literal, so you must switch between the two using a conditional if you know the state you want to use.

What's missing in the Ext.Element Class is a way to specify the css class and the state dynamically, when the desired state is known. So with the setClass method, you can do the following:



var state = checkbox.checked;
Ext.get('some_div').setClass('selected',state);


instead of:



var state = checkbox.checked;
if(state){
Ext.get('some_div').addClass('selected');
} else {
Ext.get('some_div').removeClass('selected');
}

danh2000
30 Sep 2009, 9:07 PM
or..

Ext.get('some_div')[checkbox.checked ? addClass : removeClass]('selected');

I'm not saying that there is anything wrong with adding the setClass method to Element, I'm just throwing in an alternative to the if statement you posted.

e12win
1 Oct 2009, 6:54 AM
No doubt! That's a great alternative.

Dig4Fire
4 Oct 2009, 11:08 AM
or..

Ext.get('some_div')[checkbox.checked ? addClass : removeClass]('selected');I'm not saying that there is anything wrong with adding the setClass method to Element, I'm just throwing in an alternative to the if statement you posted.

addClass/removeClass is not defined

hendricd
4 Oct 2009, 4:19 PM
addClass/removeClass is not defined

Oh, it is:


Ext.get('some_div')[checkbox.checked ? 'addClass' : 'removeClass']('selected');

aconran
5 Oct 2009, 7:48 AM
There are few situations when Ext.Element.toggleClass is the best choice. In fact, just willy nilly toggling anything is risky because you're assuming that whatever the current state, you want it to be the opposite. That's messy in most cases.


Agreed, what do you think about adding a force/override 2nd parameter to toggleClass which would take a true/false value for add/remove. If the arg was undefined it would use the standard toggleClass behavior.

As an aside I'd typically write this functionality as Dan suggested in the initial response. It's certainly more readable imo than having this 2nd param.