开发者

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


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));


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();
    });
}


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;
    }();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜