2011-01-12 2 views
2

jQuery 플러그인을 작성하고 있지만 이벤트를 처리 할 때 막혀있다.jQuery 플러그인에서 이벤트 처리하기

예를 들어 나는 사용자가 이벤트를 저장 내 처리하는 함수를 지정할 수 있도록하려면

그는이

$(".foo").bar({ 
    save: function (x,y){ 
    alert("whatever"); 
    }) 
}); 

처럼 구성 것이다 그러나 나는 호출하는 방법을 잘 모릅니다

나의 플러그인에서 인수를 전달하는 법 ...

읽어 주셔서 감사합니다!

답변

2

귀하의 플러그인 코드는 다음과 같이 보일 것입니다 : 당신이 사용자가 제공 한 함수를 호출 할 때

$.fn.bar = function(options) { 
    options = $.extend({}, {/*your default options*/}, options); 
}); 

, 호출 :

options.save(x, y); // or whatever x and y are 

을 당신이 전화를 할 경우 함수를 사용하여 변수 this이 해당 함수 내에서 유용한 의미를 갖도록하려면 call :

options.save.call(somevar, x, y); 

이 메시지는 somevar으로 콜백 내의 this을 설정합니다. 예를 들어, 당신이 bar가에 호출되었음을 선택을 할 수있는 콜백을 원한다면, 당신은 같은 것을 할 수 options.save.call(this, x y);

+1

니스 설명을,하지만 당신은 플립 할 것 '$ .extend'에서'options'와'defaults'의 위치를 ​​찾습니다. : o) – user113716

+0

@patrick 좋은 캐치 - 나는 거기에 들어가기 위해 어떤 선택을 할 것인지를 결정하려고 애를 썼고 그들이 들어간 순서를 완전히 잊었다. – lonesomeday

2
(function($) { 
    $.fn.bar = function(opts) { 
      // reference the function from the options passed 
     var theFunc = opts.save; 
      // call the function 
     theFunc(); 
     // or call the function from the context of the jQuery object 
     // and pass it the proper arguments 
     theFunc.call(this, 'someX', 'someY'); 
    }; 
})(jQuery); 
1

시도 할 수 :

(function($) { 
    $.fn.bar = function(options) { 

     // Extend default config with config object passed at invocation time 
     options = $.extend({ 
      ... 

     }, options); 

     // Check that Callback function has been passed 
     if (options.save) { 

      var newVar = ...; 

      // Delegate the function to some variable (it will act as *this* in the called 
      // function). You can pass few arguments as well 
      options.save.call(newVar, arg1, arg2) 
     } 

    }; 
})(jQuery); 
관련 문제