Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to make sure a jQuery plugin won't ever overwrite a jQuery native method?

I'm writing a jQuery plugin, and I was wondering how to make sure that I don't ever overwrite a future jQuery native method.

For example, my plugin is called Foo and usage is $('selector').foo().

jQuery 2.6 has noticed the popularity of Foo and decided that it will include it in the core package. It too is used via $('selector').foo().

I don't want my Foo to overwrite jQuery's native Foo (or else clash).

This is what I came up with...

(function($) {

  // If jQuery adds this method, we don't want to overwrite it
  if (typeof $.foo === 'function') {
    return;
  };

  $.fn.foo = function() {
     // Foo
  };  

})(jQuery);

Would this be the best way to do it?

like image 453
alex Avatar asked Nov 28 '10 09:11

alex


People also ask

What do you mean by jQuery how a plugin is used in jQuery?

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.

What is $j in jQuery?

The $ represents the jQuery Function, and is actually a shorthand alias for jQuery .

Where do I put jQuery plugins?

How to use Plugins. To make a plug-in's methods available to us, we include plug-in file very similar to jQuery library file in the <head> of the document. We must ensure that it appears after the main jQuery source file, and before our custom JavaScript code.


2 Answers

You can skip the if statements and build definition-checking into your function declaration.

(function($){

  $.fn.foo = $.fn.foo || function () {
    // only used if $.fn.foo is undefined
  }

})(jQuery)
like image 153
Adam Lassek Avatar answered Nov 07 '22 09:11

Adam Lassek


I think you would be better off with:

  if ($.foo !== undefined) {
    alert('there is something at foo');
    return;
  };

The reason being, your plugin could look like this:

$.foo = {
     doSomething: function() { /* do something*/ },
     doSomethingElse: function() { /* do something else*/ }
  }; 

The typeof the above is not function, but object, so the condition in your example will not behave as you expect.

like image 43
karim79 Avatar answered Nov 07 '22 11:11

karim79