Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's proper jQuery plugin practice?

Don't be afraid to use any technical jargon or low-level explanations for things, please. I'm savvy enough with computer architecture and low-level programming languages to comprehend any optimizations or memory management techniques, as well as complex structures (classes, member variables, etc.)

My primary focus of code is web-based applications. I work with PHP a lot and I've been learning CSS quickly. Javascript is currently my bottleneck, however. I know enough Javascript to do just about anything sans frameworks (DOM manipulation, AJAX queries, etc.). I also know that I can make my code run quicker, optimize it for specific cases, and I can shrink the over-all size of my code (no external script to include) by manually coding everything. However for ease of reading by other programmers and for speed of coding I'm trying to learn at least one Javascript framework.

After reading through the documentation on a number of frameworks and looking at some tutorials, I preferred jQuery. It allowed for very powerful iterative code in a single line and it had a very small chance of global variable namespace collision. From what I could tell, the ONLY global variable declared is the $ variable and everything else happens within this namespace, and there were even ways to access the namespace without this variable if you wanted to have two frameworks side-by-side. It also had a very small file to include (24 kilobytes gzipped) which means less server load.

My question is what are good practices in creating a jQuery plugin? If I were to start coding websites in jQuery, how should I go about it for the best interoperability and design? I want to ensure that my code can run along-side any other jQuery without interference, it's possible to build plugins off of my code, and I minimize use of the jQuery namespace so that I don't steal variables that might be used by another script.

like image 402
stevendesu Avatar asked Sep 30 '10 19:09

stevendesu


People also ask

What are jQuery plugin how do we use them?

A jQuery plugin is simply a new method that we use to extend jQuery's prototype object. By extending the prototype object you enable all jQuery objects to inherit any methods that you add. As established, whenever you call jQuery() you're creating a new jQuery object, with all of jQuery's methods inherited.

Do I need jQuery for WordPress?

jQuery is a JavaScript library that can make front-end development a lot easier for developers. This is great, because many plugins and themes use jQuery in their front-end design and development. However, WordPress itself also uses jQuery.

What is the advantage of using jQuery plugin?

jQuery makes use of powerful, clean, and simple syntax that makes it easier to pick the DOM elements on the webpage that you want to change with JavaScript and enable you to chain effects and actions together for effective code. It is common to replace dozens or more JavaScript lines with one line of jQuery code.


2 Answers

Read the jQuery plugin authoring suggestions, also look at the unminified jQuery. Notice the last line: window.jQuery = window.$ = jQuery; So there are two global variables window.jQuery and window.$. To delve into this issue a little deeper, read more about the documentation on using jQuery with other libraries and jQuery.noConflict():

  // Trigger no conflict mode.
$.noConflict();
  // Code that uses other library's $ can follow here.

For writing plugins, make sure to pay special attention to the section called Maintaining Chainability (since jQuery makes use of chainability so nicely). You have to explicitly return this in your plugins to maintain chainability. Additionally, speaking of clashing with other variables, make sure you stop your plugin from clashing with other code by using a closure:

  // Use a closure so you can use the dollar sign in your plugin, 
  //   but you don't clash with other uses of the dollar sign in the script
  //   around where you define your plugin (other libraries, etc.)
(function( $ ){

    // Adding your plugin to jQuery
  $.fn.yourPlugin = function() {  

      // Maintain chainability
    return this.each(function() {

      // ...

    });

  };
}( jQuery ));

There's a lot of other great information on that plugin authoring page. The above is just the bare bones. There's info on defaults and options, namespacing, and many other things.

Also, if you're concerned about your variables clashing, you can also make use of closures for you own "regular" code... not just jQuery plugins. To do this, enclose your script in a self invoking anonymous function:

(function() {
    var ...  // these vars will not clash with 
             // anything outside this anonymous function

    // You can do your jQuery in here if you need to access
    //   the local vars:
    $(function() { ... });

}());

For example:

// global 'clash'
var clash = "test";

(function() {
    // local 'clash'
    var clash = "something else";
    // this 'clash' shadows but doesn't change the global 'clash'
}());

alert(clash);
// The global 'clash' has stayed unaffected by the local `clash`
// Output: test

jsFiddle example

like image 141
Peter Ajtai Avatar answered Sep 21 '22 16:09

Peter Ajtai


You can add plugin methods without using the extend method:

jQuery.fn.myPlugin = function(opts) { ... } 

You can use the extend: if you're just looking to extend the jQuery object with multiple functions you would do:

jQuery.extend({ 
   funcName: function(){ 
       //function code 
   }, 
   funcName2: function(){ 
       //function code 
   } 
}); 

"jQuery.extend adds a set of properties to the jQuery object. jQuery.fn.extend adds a set of properties to the jQuery.fn object (which is then accessibly via $().foo)."

jQuery.fn is a shortcut for jQuery.prototype.

The official documentation on plugins: http://docs.jquery.com/Plugins/Authoring

Mike Alsup has this good tutorial/pattern discussion:http://www.learningjquery.com/2007/10/a-plugin-development-pattern

EDIT: One other note, be careful of your names with use of packers/minimizers - test on the one of your choice in this regard.

like image 24
Mark Schultheiss Avatar answered Sep 19 '22 16:09

Mark Schultheiss