1

I'm creating jQuery plugin:

$.fn.myGrid = function () {

    return ???;
}

I want the return value of myGrid to include an add function, so that I can use it in the following way;

var grid = $(".myGrid").myGrid();
grid.add();

How can I do this? How I have to declare the add function? And what do I have to return in myGrid plugin?

I'd also be happy to have something that works like this;

$.myGrid.add();

Is it possible?

3 Answers 3

3

One approach you could use is this;

$.fn.myGrid = function () {
    var that = this;

    return {
        add: function () {
            that.after('<h2>Here I am, adding something'); // Note `that` rather than `this`.
        },
        remove: function () {
            that.next().remove();
        }
    };
}

It's important to capture the this variable, because otherwise the methods on the object you return from your myGrid() function will not be able to access the jQuery object you invoked myGrid() on.

See the code in operation here; http://jsfiddle.net/HpeS8/

Sign up to request clarification or add additional context in comments.

Comments

0
        (function ($) {
             var methods = {
                init: function () {
                  //Initilize
             },
             var add = {
                 //Do something
             }
              $.fn.myGrid= function (method) {
                    if (methods[method]) { 
                        return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
                   }
                   else if (typeof method === 'object' || !method) { 
                        return methods.init.apply(this, arguments); 
                   }
        else { $.error('Method ' + method + ' does not exist on jQuery.myGrid'); }
    };
})(jQuery);

Call like this

var grid = $(".myGrid").myGrid();
grid.myGrid("add");

Comments

0

Usually, the best convention to write a plugin is something like this :

$.fn.pluginName = function(){
    // return the same object to preserve chainability
    // and also apply the plugin's functionality to all the
    // dom elements in this jquery collection
    return this.each(function(i,el){
       // do whatever you want with $(el)
    });
};

If you are writing a plugin that returns a value instead of manipulating in some way the current object (say like width works), you should return that value instead of the current object reference (this) :

$.fn.maxWidth = function(){
    var max = 0;
    this.each(function(i,el){
       var w = $(el).width(); 
       if(w > max)
           max = w;
    });
    return max;
};

If you want to give the user the possibility to access & modify your plugin functionality, you should definitely preserve chainability (I mean to return this and not some other object containing you plugin's api) and expose the plugin's API to the user through the jQuery element's data method.
Here's an example. Lets say that we're making a video player jquery plugin. We want to preserve chainability, but still be able to access the core functions of this plugin.
The right way to do this would be something like this :

$.fn.videoPlayer = function(){
    var api = {
        play : function(){/*...*/},
        pause : function(){/*...*/},
        stop : function(){/*...*/}
    };  

    return this.each(function(i,el){
       $(el).data('videoPlayerApi',api);
    });
};

An usage example which demonstrates my point :

$('video')
    // initialising the plugin
    .videoPlayer()
    // the return value is the original jQuery object,
    // so we can still call jQuery methods on it
    .css('opacity',1)
    // select the first video
    .eq(0)
        // access the first video's plugin api
        .data('videoPlayerApi')
            // start only the first video
            .start();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.