2013-02-18 55 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