モーダル ボックスを表示するプラグインを作成しています。その中で、htmlにイベントを割り当てて、そのボックスの外側をクリックすると閉じる必要があります。プラグインが任意のイベント ハンドラから呼び出されると、 body に伝播され、終了関数が呼び出されます。プラグイン内から伝播されたイベントを停止したい。ユーザーにイベントハンドラーに event.stopPropagtion() を追加するように依頼することはできません。
私が行った1つのハックは、バインディングクローズイベントに setTimeout を追加することですが、状況によっては失敗する可能性があることを知っています。
それを達成する方法はありますか?
サンプルコード:
(function ($, window, document, undefined) {
$.fn.modelBox = function (option) {
var myoptions = $.extend({}, $.fn.modelBox.defaults, option);
methods['show'].call(this, myoptions);
return this;
};
//default options
$.fn.modelBox.defaults = {
//default options
}
//internal method
var clickEvent=function(e){
modelBox=e.data.modalBox;
methods['close'].call(modelBox);
};
var methods={
show:function(option){
var elm=this,
elm.show();
elm.bind('click',function(e){
e.stopPropagation();
});
setTimeout(function(){$('html').bind('click',{modalBox:elm},clickEvent)},1000);
//want to achieve this without time out
},
close:function(){
var elm=this;
elm.css('display','none');
$('html').unbind('click',clickEvent);
}
}
})(jQuery, window, document);
$(document).ready(function(e) {
$('#testBut').click(function(e) {
$('#testDiv').modelBox();
});
});
HTML
<div id="testDiv"></div>
<input type="button" id="testBut" />
CSS
#testDiv{
width:400px;
height:400px;
background:#CCC;
}