2011-12-22 4 views
2

텍스트 상자에 첨부 할 수있는 jQuery 플러그인을 만들고 싶습니다. 사용자가 특정 키 조합을 입력하면 변수가 포함 된 콜백 함수를 호출 할 수 있습니다. 입력 된 키 조합에 따라 설정됩니다. 나는 루비 배경에서 왔어. 그리고 이것이 Javascript/jQuery에서도 가능한지 확실하지 않다. 다음은 그 예입니다.jQuery 플러그인/자바 스크립트에서 변수 생성하기

$('textbox').attach_my_plugin(function(){|key_combo_var| 
    // do something with key_combo_var... 
}); 

어떻게하면됩니까? 플랜 B는 key_combo_var을 요소의 .data()에 붙여야합니다. 이보다 더 좋은 방법이 있을까요?

답변

2

이것은 완전히 가능합니다. 비록 당신은 많은 세부 사항을주지는 않지만 (어떤 행동은 무엇인가?).

좋은 시작이 사이트는 자신의 플러그인을 만들기 시작하는 방법을 제공이 jQuery plugin boilerplate

입니다. 것은 잘 문서화되어 있으므로 자바 스크립트/jquery 코드를 읽을 수 있다면 너무 어렵지 않을 것입니다.

내가 원하는 것을 조금 더 자세하게 설명해 주시면, 더 자세히 구현할 수 있도록 도와 드리겠습니다.하지만 지금은 조금 흐릿합니다.


예를

으로 나는 상용구 당신이 후 찾고 어떻게해야 플러그인의 예를 사용하여 만들었습니다. 최소한 이것은 당신에게 좋은 출발을 줄 것입니다.

기본적으로 ctrl-shift-a를 누르면 콜백이 실행됩니다.

jsfiddle에 실시간으로 테스트 할 수 있습니다.

;(function ($, window, document, undefined) { 

    var pluginName = 'callbackOnKey', 
     defaults = { 
      // define a default empty callback as default 
      callback: function() {} 
     }; 

    function Plugin(element, options) { 
     this.element = element; 
     this.options = $.extend({}, defaults, options) ; 

     this._defaults = defaults; 
     this._name = pluginName; 

     this.init(); 
    } 

    Plugin.prototype.init = function() { 

     var $this = $(this.element), 
      keydownHandler = function(e) { 

       // in here, 'this' is the plugin instance thanks to $.proxy 
       // so i can access the options property (this.options.callback) 

       // if key combination is CTRL-SHIFT-a 
       if (e.ctrlKey && e.shiftKey && e.which === 65 && this.options.callback) { 

        // execute the callback 
        this.options.callback.apply(this); 

       } 

      }; 

     // bind the handler on keydown 
     // i use $.proxy to change the context the handler will be executed 
     // with (what will be 'this' in the handler). by default it would 
     // have been the input element, now it will be the plugin instance 
     $this.bind('keydown', $.proxy(keydownHandler, this)); 

    }; 

    $.fn[pluginName] = function (options) { 
     return this.each(function() { 
      if (!$.data(this, 'plugin_' + pluginName)) { 
       $.data(this, 'plugin_' + pluginName, new Plugin(this, options)); 
      } 
     }); 
    } 

})(jQuery, window, document); 

// use the plugin and pass a callback function 
$('#myinput').callbackOnKey({ 
    callback: function() { alert("It's working :o)"); } 
}); 
+0

명확성을 위해 제 질문이 업데이트되었습니다. 보일러 플레이트를 살펴보면, 플러그인 사용자는 플러그인에 옵션으로'function (key_combo_var) {...}'를 지정할 수 있고, 플러그인 코드에서부터 나는 전달 된 set 변수로 그 함수를 호출 할 수 있다고합니다 . 이 올바른지? 시간이되면 한번 시도해 보겠습니다. – Suan

+1

정확합니다. 이 메커니즘을 * 콜백 *이라고합니다. 예를 들어, jQuery 자체는 애니메이션을 마친 후 또는 Ajax 요청이 성공한 후 사용자가 일부 코드를 실행할 수 있도록하기 위해 많이 사용합니다. 이 기사 [http://jquery-howto.blogspot.com/2009/11/create-callback-functions-for-your.html]와이 다른 [질문] (http://stackoverflow.com/questions)을 참조하십시오./483073/get-a-better-understanding-of-callback-functions-in-javascript)를 참조하십시오. –

관련 문제