Here is the jQuery way to do this:<p><a href="http://docs.jquery.com/Plugins/Authoring" rel="nofollow">http://docs.jquery.com/Plugins/Authoring</a><p>Plus Event Binding:<p><a href="http://blog.rebeccamurphey.com/2009/12/03/demystifying-custom-events-in-jquery/" rel="nofollow">http://blog.rebeccamurphey.com/2009/12/03/demystifying-custo...</a>
Thanks for the post.<p>I know the introduction is a bit long, sorry. I wrote it while I was hacking and I think I was even drinking some wine during that process, so... I'll write a shorter, clearer introduction soon, I promise.<p>The problems that occur when your JavaScript (jQuery) code starts piling up are nothing new. I've been finding ways to organize my code for ages.<p>The idea behind behaviors is simple really:<p>1. Encapsulate some type of functionality within a good old function.
2. "Attach" this function to some elements as their "behavior".
3. Methods and properties of all behaviors can be accessed from anywhere, which allows interaction.<p>It's a simple object-oriented philosophy and it's nothing new. I just think it would be nice to have a standard way of organizing huge piles of JavaScript without having to use some huge JS framework or moving too far away from the jQuery coding style.
Why wouldn't I just do:<p><pre><code> $.fn.misbehave = function () { alert('Oh behave!');}
$('.bad-behavior').misbehave();</code></pre>
?<p>What is gain by adding an extra "object-oriented" wrapper around standard jquery functionality?
Some things to keep in mind:<p>-Once you apply a behavior to an element, there is no way to remove it<p>-There is no way to access the behavior by type, so if you add two different behaviors to an element, you can't (or at least, from what I can glean from the documentation) access one of the specific behaviors. This could get problematic if you have two different behaviors with identically named properties.<p>Just like events, being able to apply and remove things like this is very helpful.
nice. I don't 100% understand it or how you would use it and why you would use it and not just write jquery code and structure it logically,... but then again I'm constantly finding my jquery code to slowly becoming big and using global variables and stuff to encapsulte objects' behavior... but unfortunately, I don't really understand this enough...