如何在自己内部调用jQuery插件方法?

时间:2011-10-13 05:53:46

标签: jquery plugins

这样的jQuery插件:

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

...

如何在方法show

中调用方法init

3 个答案:

答案 0 :(得分:1)

您可以使用proxy(),就像bind()一样,只有它不需要垫片才能支持它...

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

答案 1 :(得分:0)

您可以使用闭包并捕获当前对象的上下文(this):

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

或者您也可以使用.bind()方法并将参数传递给回调\

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

或直接使用.click()方法:

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

答案 2 :(得分:0)

首先,您的代码显示您要在show的点击事件中调用#something

其次,当您在init的上下文中执行时,除非您使用其他对象代替methods.init.call(...)...,否则this将为methods 。最有可能的是,您将使用语句methods.init()。如果您只是将对象methods作为插件传递给某个jQuery小部件,那么这是正确的假设。以下内容适用于这种情况:

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

除非您想使用click事件。在这种情况下,请使用:

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

如果您希望运行methods.init.call(...),那么您需要确保事先设置闭包范围以跟踪原始methods对象:

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