2013-02-18 56 views
3

我有一个插件,每次点击指定的链接都会打开一个模式。我在插件的init()函数中附加了click事件,然后运行插件的另一个函数。jQuery插件:如何在点击范围内调用并保持插件功能

虽然问题是插入函数调用点击不能访问插件的其他属性。它似乎在窗口的范围内调用,而不是插件。

因此在此示例中,toggleModal()无法访问this.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); 

回答

1

这不是窗口,但jQuery对象你结合(如什么jQuery不会的产物)。 jQuery包含一个名为$.proxy的有用方法来解决此问题:

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

非常感谢,完美地工作。有没有更好的方法来做到这一点?我对制作jQuery插件并不是很熟悉,我觉得在其他插件中很少看到$ .proxy。有没有更好的方法将点击事件附加到提供给插件的元素? – 2013-02-18 03:34:18

+0

@LucasRaines我根本没有发现这个方法有什么问题。通常情况下,插件控制仅限于插件调用(例如,您可以调用'$(“element”).modal('toggleModal',true)'或类似的东西,但是您可以使用任何适合您和任何人的作品使用你的插件。 – 2013-02-18 03:35:58

+0

好的,很好,谢谢你的信息。 – 2013-02-18 03:38:28