간단한 jQuery 플러그인을 작성했습니다. 내 플러그인은 '앞으로'버튼이있는 HTML 요소를 만듭니다. 버튼은 몇 가지 작업을 수행하며 사용자가 하나를 설정하면 콜백을 호출 할 수 있습니다.플러그인 초기화 후 플러그인에 콜백 추가하기
$('selector').myPlugin({onForward: function(){console.log('forward'); } });
을 그리고 그 작업 괜찮아요 :
나는 (옵션 1)과 같은 초기 단계에서 콜백을 추가 할 수 있습니다.
하지만 내가 만든 플러그인 (옵션 2) 후 콜백을 설정하려고하면 : 플러그인 콜백 실행되지 않고있는 상태입니다
var $plugin = $('selector').myPlugin();
$plugin.myPlugin('onForward',function(){console.log('forward'); });
.
콜백 저장에 사용하는 'defaults'변수가 있습니다. "나는"onForward "방법을 설정하면
var defaults = {
onForward: function(){}, // initialize with empty callback
}
, 디버거를 사용하여, 나는 defaults.onForward의 값이 새로운 콜백 설정되어 볼 수 있지만 버튼이 트리거 될 때, 그것은 버튼과 같은 보인다 '내가 이전에 설정 한 메서드를 잊어 버렸고 초기화에 사용 된 기본 빈 메서드를 사용합니다. 여기
플러그인 코드를 싹둑입니다 :(function($){
$.fn.myPlugin = function(methodOrOptions){
var $self = $(this);
var defaults = {
onForward: function(){},
};
var methods = {
init: function(options){
$.extend(defaults,options);
$self.find('button#forward').on('click',events.forward);
return $self;
},
onForward: function(callback){
defaults.onForward = callback; // setting the callback after initialization
},
};
var events = {
forward: function(){
// do stuff and call the callback
defaults.onForward();
}
}
if(methods[methodOrOptions]){
return methods[methodOrOptions].apply(this,Array.prototype.slice.call(arguments, 1));
}
else if(typeof(methodOrOptions) === 'object' || !methodOrOptions){
return methods.init.apply(this,arguments)
}
else{
console.log('error: method: '+methodOrOptions+' does not exists');
}
})(jQuery);
내가 잘못 뭐하는 거지? Thx
@ ced-b. 감사합니다. 나를 위해 완벽하게 작동합니다. – YyYo