2

I want to create a jQuery plugin which can be attached to a text box, and after the user enters a certain key combination, a callback function can be called, with a variable that is set based on the entered key combo. I'm coming from a Ruby background, and I'm not sure if this is even possible in Javascript/jQuery. Here's an example:

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

How would I achieve this? Plan B is to stick key_combo_var into the .data() of the element. Would there be a better way than this?

Suan
  • 34,563
  • 13
  • 47
  • 61

1 Answers1

2

This is totally possible. Although you don't give much details (what certain action ?).

A good start is this jQuery plugin boilerplate

The site provides a way to start creating your own plugin. The thing is pretty well documented so if you can read javascript/jquery code, it should not be too difficult.

If you provide a bit more details on what you'd like to do, I can help you further implementing it but right now it's a bit too blurry.


As example

I have created using the boilerplate an example of a plugin that should do what you're looking after. At least this will give you a good start.

It basically will execute the callback when you press ctrl-shift-a.

You can test it live on 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)"); }
});
Didier Ghys
  • 30,396
  • 9
  • 75
  • 81
  • Updated my question for clarity. Looking at the boilerplate, it seems that the plugin user can specify `function(key_combo_var){...}` as an option into the plugin, and from my plugin code I can then call that function with the set variable passed in at will. Is this correct? I'll try it out once I have the time. – Suan Dec 22 '11 at 23:02
  • 1
    Exactly. This mechanism is called *callbacks*. jQuery itself uses this a lot, for instance, to allow users executing some code after an animation has finished, or when an ajax request is successful. See this [article](http://jquery-howto.blogspot.com/2009/11/create-callback-functions-for-your.html) and this other [question](http://stackoverflow.com/questions/483073/getting-a-better-understanding-of-callback-functions-in-javascript) for more information. – Didier Ghys Dec 22 '11 at 23:32