2012-01-07 2 views
0

jQuery 플러그인을위한 일종의 기본 프레임 워크에서 일하고 있습니다. 나는 jQuery Plugins/Authoring 예제의 구조를 기초로하여 here을 찾았다.메소드 및 콜백이 포함 된 jQuery 플러그인

(function($){ 
    var methods = { 
    init : function(options) { 
     var defaults = { 
      // place default settings for plugin here 
     } 

     var options = $.extend(defaults, options); 

     return this.each(function(){ 
      var $this = $(this), 
       data = $this.data('PLUGINNAME'); 

      if (! data) { 
      // do more setup stuff here 
      } 
     }); 
    }, 

    destroy : function() { 
     return this.each(function(){ 
     // do stuff to destroy any function binding 
     }) 
    }, 

    update : function(content) { 
     return this.each(function() { 
      //do your update stuff here 
     }) 
    } 
    }; 

    $.fn.PLUGINNAME = function(method) { 
    if (methods[method]) { 
     return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
    } else if (typeof method === 'object' || ! method) { 
     return methods.init.apply(this, arguments); 
    } else { 
     $.error('Method ' + method + ' does not exist on jQuery.PLUGINNAME'); 
    }  
    }; 
})(jQuery); 

지금 알아 내기 위해 노력하고있어 조각 플러그인 호출에 콜백 함수를 추가하는 방법입니다 :

는 여기에 내가 짓고 있어요 구조의 더 단순화 된 버전입니다. 나는이 같은 다른 매개 변수가 필요합니다 알고 :

$.fn.PLUGINNAME = function(method, callback) { 

을하지만 난 그게 내가 현재 무엇을 기반으로 구현하는 방법에 대한 이동하는 방법을 잘 모르겠어요.

+0

이 콜백은 무엇이고 서명은 무엇입니까? –

+0

콜백이해야 할 일은 중요하지 않습니다. 어쩌면 그것은 플러그인이 일부 스크립트 (예 : getJSON 호출)를 실행할 때까지 기다려야 만 함수가 페이지의 일부 요소를 처리 할 수 ​​있습니다. –

답변

1

콜백 함수를 호출하려면 .call 메서드를 사용할 수 있습니다.

init : function(options, callback) { 
    callback.call(this, options); 

예에서 필자는 옵션을 전달했지만 필요한 경우 전달할 수 있습니다.

+0

하지만 플러그인이 'return this.each (function() {'return)을 사용하면 플러그인의 연결 가능성에 대한 아이디어가 어떻게 작동합니까? –

+0

콜백은 "this"를 반환하지 않는 한 "this this 콜백이 허용하는 jQuery 기본 함수 중 일부를 볼 수 있습니다. –

+0

그래서 내 업데이트 메소드는 다음과 비슷하게 보일 것입니다. "update : function (options, callback) { ? this.each (함수() { callback.call (이 옵션) 이}) 반환 . }'그리고 거기는 플러그인 자체에 어떤 변화 –

관련 문제