Callum Linington
Callum Linington

Reputation: 14417

Extending jQuery writing Plugins

When you write a plugin for jQuery you do:

(function ($) {
    $.fn.myFunc = function () {

    };
}(jQuery));

I expect that the $ allows the functions below to be assigned to it. fn are a list of the functions that are allowed to be executed.

I'm not sure what jQuery does, I think it still allows you to use jQuery.myFunc??

How do you achieve something like this, but for just plain javascript, no libraries?

I carry a single javascript file between all my web pages.

Here's the question: I want to be able to use a set of custom functions really easily, like jQuery can.

For example in jQuery:

$.map();

I want to be able to do something like:

$.doSomething();

where $ is my own custom what ever symbol, and I can also attach other functions to it.

The main idea, is to achieve something that cannot interfere with other things written, so clashing functions etc.

Upvotes: 2

Views: 67

Answers (2)

user3802027
user3802027

Reputation: 1

To use $.extend();

    (function ($) {
        $.fn.myFunc1 = function (text) {
            alert(text);
        };

        $.extend({
            myFunc2: function (text) {
                alert(text);
            }
        }); 
    }(jQuery));

    $('div').myFunc1('Ho');

    $.myFunc2('Hey');

Upvotes: 0

sdespont
sdespont

Reputation: 14025

To use $.yourfunction, you need to extend $

$.fn permits to extend $('selector').your function

Here is a working exemple : http://jsfiddle.net/UQTY2/207/

(function ($) {
    $.fn.myFunc1 = function (text) {
        alert(text);
    };

    $.myFunc2 = function (text) {
        alert(text);
    };    
}(jQuery));

$('div').myFunc1('Ho');

$.myFunc2('Hey');

Upvotes: 2

Related Questions