2011-01-28 6 views
0

플러그인 내부에서 jQuery-UI를 사용 중이고 대화 상자의 이벤트에 대한 콜백 함수를 설정하려고합니다. 대화 상자가 닫힐 때가 아니라 페이지가로드 될 때 즉시 (2x) 실행되므로이 ​​작업을 잘못하고있는 것으로 생각됩니다.플러그인 내에서 jQuery-UI 대화 상자가 콜백 실행을 즉시 사용합니다.

내가 잘못 뭘하는지에 페이지 코드

$(document).ready(function() { 
    $('.photoLink').photoDialog({ 
     url: 'http://tvrecappersanonymous.files.wordpress.com/2010/03/doozer2.jpg', 
     title: 'Doozer', 
     onClose: function() { 
      alert('Callback'); //fires 2x when page loads 
     } 
    }); 
}); 

어떤 제안을 호출 플러그인 코드는

(function($) { 

    //dynamically add UI CSS 
    var link = $('<link>'); 
    link.attr({ 
     type: 'text/css', 
     rel: 'stylesheet', 
     href: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/themes/black-tie/jquery-ui.css' 
    }).appendTo('head'); 

    //dynamically add UI JS 
    var script = $('<script'>); 
    script.attr({ 
     type: 'text/javascript', 
     src: 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js' 
    }).appendTo('head'); 

    $.fn.photoDialog = function(options) { 

     //set default settings 
     var defaults = { 
      autoOpen: false, 
      title: 'Photo Tool', 
      minHeight: 560, 
      minWidth: 540, 
      url: 'http://www.goffinmoleculartechnologies.com/images/no-image-large.png', 
      onClose: function(){} 
     }; 

     //extend options to defaults 
     var opts = $.extend(defaults, options); 

     return this.each(function() { 
      $this = $(this); 
      //create UI dialog 
      var $dialog = $('<div>') 
       .html('<img src="' + opts.url + '" width="' + opts.minWidth + '" height="' + minHeight + '" alt="" />') 
       .dialog({ 
        autoOpen: opts.autoOpen, 
        title: opts.title, 
        minHeight: opts.minHeight, 
        minWidth: opts.minWidth, 
        modal: true, 
        close: opts.onClose.call(this) //callback function 
       }); 

      //add dialog open to click function of caller 
      $this.click(function() { 
       $dialog.dialog('open'); 
       return false; 
      }); 
     }); 
    }; 
})(jQuery); 

감사합니다.

답변

2

opts.onClose 콜백 함수의 결과를 함수가 아닌 함수로 지정하기 때문입니다. 대신 인라인 함수로 래핑하십시오.

변수를 사용하여이 변수를 callback.call에 전달하십시오.

return this.each(function() { 
      var $this = $(this); 
      var that = $(this); 
      //create UI dialog 
      var $dialog = $('<div>') 
       .html('<img src="' + opts.url + '" width="' + opts.minWidth + '" height="' + minHeight + '" alt="" />') 
       .dialog({ 
        autoOpen: opts.autoOpen, 
        title: opts.title, 
        minHeight: opts.minHeight, 
        minWidth: opts.minWidth, 
        modal: true, 
        close: function(){ 
        opts.onClose.call(that) //callback function 
        } 
       }); 
:

는 return 문에 변경

관련 문제