Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vanilla JS plugin template

Tags:

javascript

Okay, we all know how to write jQuery plugins: http://docs.jquery.com/Plugins/Authoring

Can someone advise on a pure Javascript template plugin with methods and default settings?

I want to make it work with a single node and with a node array (querySelectorAll)

Something like this:

var PluginName = function(selector){
    ...
}

And call it like this:

var dropdown = new PluginName('.dropdown');

And be able to close all dropdowns like this:

dropdown.close();
like image 331
bravedick Avatar asked Jan 16 '13 15:01

bravedick


3 Answers

I've been using module patterns with inits and public methods for a little while now. Not an exact match-for-match of the jQuery plugin pattern, but quite extensible and works really well. Just recently updated it for UMD/CommonJS/AMD/etc.

You checkout my starter template here, and view a working example here.

For good measure, the full template here:

/**
 *
 * Name v0.0.1
 * Description, by Chris Ferdinandi.
 * http://gomakethings.com
 *
 * Free to use under the MIT License.
 * http://gomakethings.com/mit/
 *
 */

(function (root, factory) {
    if ( typeof define === 'function' && define.amd ) {
        define(factory);
    } else if ( typeof exports === 'object' ) {
        module.exports = factory;
    } else {
        root.Plugin = factory(root); // @todo Update to plugin name
    }
})(this, function (root) {

    'use strict';

    //
    // Variables
    //

    var exports = {}; // Object for public APIs
    var supports = !!document.querySelector && !!root.addEventListener; // Feature test

    // Default settings
    var defaults = {
        someVar: 123,
        callbackBefore: function () {},
        callbackAfter: function () {}
    };


    //
    // Methods
    //

    /**
     * Merge defaults with user options
     * @private
     * @param {Object} defaults Default settings
     * @param {Object} options User options
     * @returns {Object} Merged values of defaults and options
     */
    var extend = function ( defaults, options ) {
        for ( var key in options ) {
            if (Object.prototype.hasOwnProperty.call(options, key)) {
                defaults[key] = options[key];
            }
        }
        return defaults;
    };

    /**
     * A simple forEach() implementation for Arrays, Objects and NodeLists
     * @private
     * @param {Array|Object|NodeList} collection Collection of items to iterate
     * @param {Function} callback Callback function for each iteration
     * @param {Array|Object|NodeList} scope Object/NodeList/Array that forEach is iterating over (aka `this`)
     */
    var forEach = function (collection, callback, scope) {
        if (Object.prototype.toString.call(collection) === '[object Object]') {
            for (var prop in collection) {
                if (Object.prototype.hasOwnProperty.call(collection, prop)) {
                    callback.call(scope, collection[prop], prop, collection);
                }
            }
        } else {
            for (var i = 0, len = collection.length; i < len; i++) {
                callback.call(scope, collection[i], i, collection);
            }
        }
    };

    /**
     * Remove whitespace from a string
     * @private
     * @param {String} string
     * @returns {String}
     */
    var trim = function ( string ) {
        return string.replace(/^\s+|\s+$/g, '');
    };

    /**
     * Convert data-options attribute into an object of key/value pairs
     * @private
     * @param {String} options Link-specific options as a data attribute string
     * @returns {Object}
     */
    var getDataOptions = function ( options ) {
        var settings = {};
        // Create a key/value pair for each setting
        if ( options ) {
            options = options.split(';');
            options.forEach( function(option) {
                option = trim(option);
                if ( option !== '' ) {
                    option = option.split(':');
                    settings[option[0]] = trim(option[1]);
                }
            });
        }
        return settings;
    };

    // @todo Do something...

    /**
     * Initialize Plugin
     * @public
     * @param {Object} options User settings
     */
    exports.init = function ( options ) {

        // feature test
        if ( !supports ) return;

        // @todo Do something...

    };


    //
    // Public APIs
    //

    return exports;

});
like image 118
Chris Ferdinandi Avatar answered Sep 30 '22 04:09

Chris Ferdinandi


I would say that you want a JavaScript class.

var PluginName = function(selector){
    // Constructor here
    this.el = document.querySelector(selector);
}

PluginName.prototype.close = function(){
    console.log(this.el);
}

PluginName.prototype.anotherMethod = function(){
    console.log(this.el);
}

Then you can do:

var dropdown = new PluginName('.dropdown');
dropdown.close();
dropdown.anotherMethod();

One common practice to plugins is to pass an options object in the constructor. This way you can parameterize some behaviour elegantly. Example:

var dropdown = new PluginName({el:'.dropdown',slideInterval:1000, effect:'fade'});
like image 25
miguelcobain Avatar answered Sep 30 '22 04:09

miguelcobain


Look up javascript prototypal inheritance.

function PluginName(selector) {
    this.node = document.querySelector(selector);
        if (this.node == null) {
            // whoops node not found! Handle Error
        }

    return this;
}

PluginName.prototype.close = function() {
        this.var = "blah";
        // do stuff
}

var myPlugin = new Plugin(".selector")

Also this site has awesome javascript design patterns - http://addyosmani.com/resources/essentialjsdesignpatterns/book/

like image 43
Nucleon Avatar answered Sep 30 '22 06:09

Nucleon