指定したリンクがクリックされるたびにモーダルを開くプラグインがあります。プラグインの init() 関数にクリック イベントを追加すると、プラグインの別の関数が実行されます。
ただし問題は、クリック時に呼び出されるプラグイン関数がプラグインの他の属性にアクセスできないことです。代わりに、プラグインではなく、ウィンドウのスコープ内で呼び出されるようです。
したがって、この例では、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);