Ya Zhuang
Ya Zhuang

Reputation: 4660

how to call jQuery plugin's method inside itself?

a jQuery plugin like this:

var methods = {
    init: function(options) {
        $("#something").click(function() {
            //call method show
        });
    },
    show: function() {
        //show something around here.
    }
}

..

how can i call the method show inside the method init

Upvotes: 3

Views: 2252

Answers (3)

Ryan
Ryan

Reputation: 1557

First, your code shows that you want to call show inside of the click event of #something.

Second, when you're executing in the context of init, unless you say methods.init.call(...) with some other object in place of ..., then this will be methods. Most likely, you will use the statement methods.init(). This is the correct assumption if you are just passing the object methods as a plugin to some jQuery widget. The following will work in this case:

    var methods = {
        init: function(options) {
            this.show();
        },
        show: function() {}
    }

Unless you want to use the click event. In that case, use:

    var methods = {
        init: function(options) {
            $('#something').click(function() {
                this.show();
            }, this);  // propogate this into click handler
        },
        show: function() {}
    }

If you expect that you will run methods.init.call(...), then you will need to make sure to set up a closure scope beforehand to keep track of the original methods object:

    var methods = function() {
        // setup closure scope
        var that = {};  // keep track of methods object
        that.init = function() {
            that.show();
        };
        that.show = function() {

        };

        // return object with closure scope... will become `methods`
        return that;
    }();

Upvotes: 0

alex
alex

Reputation: 490153

You could use proxy(), which is like bind() only it doesn't need a shim for where it's not supported...

$("#something").click($.proxy(function() {
        // `this` is the same as `this` outside the function now.
        this.show();
    }, this));

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You could use a closure and capture the context of the current object (this):

init: function(options) {
    var _this = this;
    $('#something').click(function() {
        _this.show();
    });
}

or you could also use the .bind() method and pass arguments to the callback\

init: function(options) {
    $('#something').bind('click', { _this: this }, function(evt) {
        evt.data._this.show();
    });
}

or directly with the .click() method:

init: function(options) {
    $('#something').click({ _this: this }, function(evt) {
        evt.data._this.show();
    });
}

Upvotes: 0

Related Questions