Javascript jQuery插件:如何在单击时调用插件函数并将其保持在范围内

Javascript jQuery插件:如何在单击时调用插件函数并将其保持在范围内,javascript,jquery,jquery-plugins,plugins,Javascript,Jquery,Jquery Plugins,Plugins,我有一个插件,它会在每次点击指定链接时打开一个模式。我将click事件附加到插件的init()函数中,该函数随后运行插件的另一个函数 但问题是单击时调用的插件函数无法访问插件的其他属性。相反,它似乎是在窗口范围内调用的,而不是在插件范围内调用的 因此在本例中,toggleModal()无法访问此.config.container。 如何在单击时触发插件函数,该函数位于插件的作用域内 插件如下所示: ;(function($, window, document, undefined){ var

我有一个插件,它会在每次点击指定链接时打开一个模式。我将click事件附加到插件的init()函数中,该函数随后运行插件的另一个函数

但问题是单击时调用的插件函数无法访问插件的其他属性。相反,它似乎是在窗口范围内调用的,而不是在插件范围内调用的

因此在本例中,toggleModal()无法访问此.config.container。

如何在单击时触发插件函数,该函数位于插件的作用域内

插件如下所示:

;(function($, window, document, undefined){

var Modal = function(elem, options){
    this.elem = elem;
    this.$elem = $(elem);
    this.options = options;
    this.metadata = this.$elem.data('modal-options');
};

Modal.prototype = {
    defaults: {
        container: '#pageModal'
    },

    init: function() {
        this.config = $.extend({}, this.defaults, this.options, this.metadata);


        this.$elem.bind('click', this.toggleModal);

        if(!$(this.config.container).length) {
            this._build();
        }

        return this;
    },

    toggleModal: function() {
        $(this.config.container).fadeIn();
        return false;
    },

    _build: function() {
        var structure = '<section id="' + this.config.container.replace('#', '') + '"><section class="modalContent"></section></section>';

        $(structure).appendTo($('body')).hide();
    },
}

Modal.defaults = Modal.prototype.defaults;

$.fn.modal = function(options) {
    return this.each(function() {
        new Modal(this, options).init();
    });
};

})(jQuery, window, document);
;(函数($,窗口,文档,未定义){
var模态=功能(要素、选项){
this.elem=elem;
这个.$elem=$(elem);
this.options=选项;
this.metadata=this.$elem.data('modal-options');
};
Modal.prototype={
默认值:{
容器:“#pageModal”
},
init:function(){
this.config=$.extend({},this.defaults,this.options,this.metadata);
this.$elem.bind('click',this.toggleModal);
if(!$(this.config.container).length){
这个;
}
归还这个;
},
toggleModal:function(){
$(this.config.container).fadeIn();
返回false;
},
_构建:函数(){
var结构=“”;
$(结构).appendTo($('body')).hide();
},
}
Modal.defaults=Modal.prototype.defaults;
$.fn.modal=功能(选项){
返回此值。每个(函数(){
新模态(this,options).init();
});
};
})(jQuery、窗口、文档);

它不是窗口,而是您绑定到的jQuery对象(作为jQuery功能的产物)。jQuery包含一个有用的方法,该方法称为:

this.$elem.on('click', $.proxy(this.toggleModal, this));

非常感谢,非常好用。但是有没有更好的方法?我不太熟悉jQuery插件的制作,我觉得在其他插件中很少看到$.proxy。有没有更好的方法将点击事件附加到插件提供的元素上?@LucasRaines我看不出这个方法有任何错误。通常,插件控制仅限于插件调用(例如,您将调用
$(“element”).modal('toggleModal',true)
或类似的东西,但是您可以使用任何适合您和您想要使用插件的人的东西。