About

TextExt is the main core class which by itself doesn’t provide any functionality that is user facing, however it has the underlying mechanics to bring all the plugins together under one roof and make them work with each other or on their own.

jQuery Integration

TextExt integrates as a jQuery plugin available through the $(selector).textext(opts) call. If opts argument is passed, then a new instance of TextExt will be created for all the inputs that match the selector. If opts wasn’t passed and TextExt was already intantiated for inputs that match the selector, array of TextExt instances will be returned instead.

// will create a new instance of `TextExt` for all elements that match `.sample`
$('.sample').textext({ ... });

// will return array of all `TextExt` instances
var list = $('.sample').textext();

The following properties are also exposed through the jQuery $.fn.textext:

  • TextExtTextExt class.
  • TextExtPluginTextExtPlugin class.
  • ItemManagerItemManager class.
  • plugins – Key/value table of all registered plugins.
  • addPlugin(name, constructor) – All plugins should register themselves using this function.

Options

TextExt provides a way to pass in the options to configure the core as well as each plugin that is being currently used. The jQuery exposed plugin $().textext() function takes a hash object with key/value set of options. For example:

$('textarea').textext({
    enabled: true
})

There are multiple ways of passing in the options:

  1. Options could be nested multiple levels deep and accessed using all lowercased, dot separated style, eg foo.bar.world. The manual is using this style for clarity and consistency. For example:

    {
        item: {
            manager: ...
        },
    
        html: {
            wrap: ...
        },
    
        autocomplete: {
            enabled: ...,
            dropdown: {
               position: ...
            }
        }
    }
    
  2. Options could be specified using camel cased names in a flat key/value fashion like so:

    {
        itemManager: ...,
        htmlWrap: ...,
        autocompleteEnabled: ...,
        autocompleteDropdownPosition: ...
    }
    
  3. Finally, options could be specified in mixed style. It’s important to understand that for each dot separated name, its alternative in camel case is also checked for, eg for foo.bar.world it’s alternatives could be fooBarWorld, foo.barWorld or fooBar.world, which translates to { foo: { bar: { world: ... } } }, { fooBarWorld: ... }, { foo : { barWorld : ... } } or { fooBar: { world: ... } } respectively. For example:

    {
        itemManager : ...,
        htmlWrap: ...,
        autocomplete: {
            enabled: ...,
            dropdownPosition: ...
        }
    }
    

Mixed case is used through out the code, wherever it seems appropriate. However in the code, all option names are specified in the dot notation because it works both ways where as camel case is not being converted to its alternative dot notation.

ext ({})

TextExt allows for overriding of virtually any method that the core or any of its plugins use. This could be accomplished through the use of the ext option.

It’s possible to specifically target the core or any plugin, as well as overwrite all the desired methods everywhere.

  1. Targeting the core:

    ext: {
        core: {
            trigger: function()
            {
                console.log('TextExt.trigger', arguments);
                $.fn.textext.TextExt.prototype.trigger.apply(this, arguments);
            }
        }
    }
    
  2. Targeting individual plugins:

    ext: {
        tags: {
            addTags: function(tags)
            {
                console.log('TextExtTags.addTags', tags);
                $.fn.textext.TextExtTags.prototype.addTags.apply(this, arguments);
            }
        }
    }
    
  3. Targeting ItemManager instance:

    ext: {
        itemManager: {
            stringToItem: function(str)
            {
                console.log('ItemManager.stringToItem', str);
                return $.fn.textext.ItemManager.prototype.stringToItem.apply(this, arguments);
            }
        }
    }
    
  4. And finally, in edge cases you can extend everything at once:

    ext: {
        '*': {
            fooBar: function() {}
        }
    }
    

html.hidden ('<input type="hidden" />')

HTML source that is used to generate hidden input value of which will be submitted with the HTML form.

html.wrap ('<div class="text-core"><div class="text-wrap"/></div>')

HTML source that is used to generate elements necessary for the core and all other plugins to function.

item.manager (ItemManager)

Default instance of ItemManager which takes String type as default for tags.

keys ({ ... })

Hash table of key codes and key names for which special events will be created by the core. For each entry a [name]KeyDown, [name]KeyUp and [name]KeyPress events will be triggered along side with anyKeyUp and anyKeyDown events for every key stroke.

Here’s a list of default keys:

{
    8   : 'backspace',
    9   : 'tab',
    13  : 'enter!',
    27  : 'escape!',
    37  : 'left',
    38  : 'up!',
    39  : 'right',
    40  : 'down!',
    46  : 'delete',
    108 : 'numpadEnter'
}

Please note the ! at the end of some keys. This tells the core that by default this keypress will be trapped and not passed on to the text input.

plugins ([])

List of plugins that should be used with the current instance of TextExt. The list could be specified as array of strings or as comma or space separated string.

Events

The core triggers or reacts to the following events.

[name]KeyDown

Core triggers [name]KeyDown event for every key specified in the keys option that is triggered within the component.

[name]KeyPress

Core triggers [name]KeyPress event for every key specified in the keys option that is triggered within the component.

[name]KeyUp

Core triggers [name]KeyUp event for every key specifid in the keys option that is triggered within the component.

anyKeyDown

Core triggers anyKeyDown event for every key down event triggered within the component.

anyKeyUp

Core triggers anyKeyUp event for every key up event triggered within the component.

getFormData

Core triggers getFormData on every key press to collect data that will be populated into the hidden input that will be submitted with the HTML form and data that will be displayed in the input field that user is currently interacting with.

All plugins that wish to affect how the data is presented or sent must react to getFormData and populate the data in the following format:

{
    input : {String},
    form  : {Object}
}

The data key must be a numeric weight which will be used to determine which data ends up being used. Data with the highest numerical weight gets the priority. This allows plugins to set the final data regardless of their initialization order, which otherwise would be impossible.

For example, the Tags and Autocomplete plugins have to work side by side and Tags plugin must get priority on setting the data. Therefore the Tags plugin sets data with the weight 200 where as the Autocomplete plugin sets data with the weight 100.

Here’s an example of a typical getFormData handler:

TextExtPlugin.prototype.onGetFormData = function(e, data, keyCode)
{
    data[100] = self.formDataObject('input value', 'form value');
};

Core also reacts to the getFormData and updates hidden input with data which will be submitted with the HTML form.

postInit

Core triggers postInit event to let plugins run code after all plugins have been created and initialized. This is a good place to set some kind of global values before somebody gets to use them. This is not the right place to expect all plugins to finish their initialization.

postInvalidate

Core triggers postInvalidate event after the dimensions of padding on the text input are set.

preInvalidate

Core triggers preInvalidate event before the dimensions of padding on the text input are set.

ready

Core triggers ready event after all global configuration and prepearation has been done and the TextExt component is ready for use. Event handlers should expect all values to be set and the plugins to be in the final state.

setFormData

Core triggers and reacts to the setFormData event to update the actual value in the hidden input that will be submitted with the HTML form. Second argument can be value of any type and by default it will be JSON serialized with TextExt.serializeData() function.

setInputData

Core triggers and reacts to the setInputData event to update the actual value in the text input that user is interacting with. Second argument must be of a String type the value of which will be set into the text input.

Methods

$.fn.textext.addPatch(name, constructor)

  • name {String} Name of the patch.

  • constructor {Function} Patch constructor.

This static function registers a new patch which is added to each instance of TextExt. If you are adding a new patch, make sure to call this method.

$.fn.textext.addPlugin(name, constructor)

  • name {String} Name of the plugin.

  • constructor {Function} Plugin constructor.

This static function registers a new plugin which makes it available through the plugins option to the end user. The name specified here is the name the end user would put in the plugins option to add this plugin to a new instance of TextExt.

TextExt.bind(event, handler)

  • event {String} Event name.

  • handler {Function} Event handler.

Binds an event handler to the input box that user interacts with.

TextExt.focusInput()

Focuses user input on the text box.

TextExt.getFormData(keyCode)

  • keyCode {Number} Key code number which has triggered this update. It’s impotant to pass this value to the plugins because they might return different values based on the key that was pressed. For example, the Tags plugin returns an empty string for the input value if the enter key was pressed, otherwise it returns whatever is currently in the text input.

Triggers the getFormData event to get all the plugins to return their data.

After the data is returned, triggers setFormData and setInputData to update appopriate values.

TextExt.getWeightedEventResponse(event, args)

  • event {String} Event name.

  • args {Object} Argument to be passed with the event.

Abstracted functionality to trigger an event and get the data with maximum weight set by all the event handlers. This functionality is used for the getFormData event.

TextExt.hasPlugin(name) 1.1

  • name {String} Name of the plugin to check.

Returns true if specified plugin is was instantiated for the current instance of core.

TextExt.init(input, opts)

  • input {HTMLElement} Text input.

  • opts {Object} Options.

Initializes current component instance with work with the supplied text input and options.

TextExt.initPatches()

Initialized all installed patches against current instance. The patches are initialized based on their initialization priority which is returned by each patch’s initPriority() method. Priority is a Number where patches with higher value gets their init() method called before patches with lower priority value.

This facilitates initializing of patches in certain order to insure proper dependencies regardless of which order they are loaded.

By default all patches have the same priority - zero, which means they will be initialized in rorder they are loaded, that is unless initPriority() is overriden.

TextExt.initPlugins(plugins)

  • plugins {Array} List of plugin names to initialize.

Creates and initializes all specified plugins. The plugins are initialized based on their initialization priority which is returned by each plugin’s initPriority() method. Priority is a Number where plugins with higher value gets their init() method called before plugins with lower priority value.

This facilitates initializing of plugins in certain order to insure proper dependencies regardless of which order user enters them in the plugins option field.

By default all plugins have the same priority - zero, which means they will be initialized in the same order as entered by the user.

TextExt.input()

Returns jQuery input element with which user is interacting with.

TextExt.invalidateBounds()

Updates container to match dimensions of the text input. Triggers preInvalidate and postInvalidate events.

TextExt.itemManager()

Returns instance of itemManager that is used by the component.

TextExt.on([target], handlers)

  • target {Object} Optional. Target object which has traditional bind(event, handler) method. Handler function will still be executed in the current object’s scope.

  • handlers {Object} Key/value pairs of event names and handlers, eg { event: handler }.

Allows to add multiple event handlers which will be execued in the scope of the current object.

TextExt.onAnyKeyUp(e)

  • e {Object} jQuery event.

Reacts to the anyKeyUp event and triggers the getFormData to change data that will be submitted with the form. Default behaviour is that everything that is typed in will be JSON serialized, so the end result will be a JSON string.

TextExt.onGetFormData(e, data)

  • e {Event} jQuery event.

Reacts to getFormData event triggered by the core. At the bare minimum the core will tell itself to use the current value in the text input as the data to be submitted with the HTML form.

TextExt.onKeyDown(e)

  • e {Object} jQuery event.

Triggers [name]KeyDown for every keystroke as described in the events.

TextExt.onKeyUp(e)

  • e {Object} jQuery event.

Triggers [name]KeyUp and [name]KeyPress for every keystroke as described in the events.

TextExt.onSetFormData(e, data)

  • e {Event} jQuery event.

  • data {Object} Data that will be set.

Reacts to the setFormData event and populates the hidden input with will be submitted with the HTML form. The value will be serialized with serializeData() method.

TextExt.onSetInputData(e, data)

  • e {Event} jQuery event.

  • data {String} Value to be set.

Reacts to the setInputData event and populates the input text field that user is currently interacting with.

TextExt.opts(name)

  • name {String} Option name as described in the options.

Returns option value for the specified option by name. If the value isn’t found in the user provided options, it will try looking for default value.

TextExt.serializeData(data)

  • data {Object} Data to serialize.

Serializes data for to be set into the hidden input field and which will be submitted with the HTML form.

By default simple JSON serialization is used. It’s expected that JSON.stringify method would be available either through built in class in most modern browsers or through JSON2 library.

TextExt.trigger(event, ...args)

  • event {String} Name of the event to trigger.

  • …args All remaining arguments will be passed to the event handler.

Triggers an event on the input box that user interacts with. All core events are originated here.

TextExt.wrapElement()

Returns HTML element that was created from the html.wrap option. This is the top level HTML container for the text input with which user is interacting with.

Fork me on GitHub