2011-12-22 34 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