2011-12-22 39 views
2

我想創建一個可以附加到文本框的jQuery插件,並且在用戶輸入某個組合鍵後,可以調用一個回調函數,根據輸入的組合鍵設置。我來自Ruby背景,我不確定這是甚至可能在Javascript/jQuery中。以下是一個示例:在jQuery插件/ Javascript中產生變量

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

我該如何實現這一目標?計劃B將key_combo_var粘貼到元素的.data()中。會有比這更好的方法嗎?

回答

2

這是完全可能的。雖然你沒有提供太多細節(有什麼特定的行動?)。

良好的開端是這個jQuery plugin boilerplate

該網站提供了一種方法,開始創建自己的插件。這件事很好記錄,所以如果你可以閱讀JavaScript/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 2011-12-22 23:02:28

+1

沒錯。這種機制被稱爲* callbacks *。例如,jQuery本身使用了很多,例如,允許用戶在動畫完成後執行一些代碼,或者當ajax請求成功時執行一些代碼。看到這[文章](http://jquery-howto.blogspot.com/2009/11/create-callback-functions-for-your.html)和這其他[問題](http://stackoverflow.com/questions/483073 /越來越瞭解回調函數在JavaScript中)的更多信息。 – 2011-12-22 23:32:53