簡體   English   中英

香草JS插件模板

[英]Vanilla JS plugin template

好的,我們都知道如何編寫jQuery插件: http//docs.jquery.com/Plugins/Authoring

有人可以使用方法和默認設置建議一個純Javascript模板插件嗎?

我想讓它與單個節點和節點數組一起工作( querySelectorAll

像這樣的東西:

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

並稱之為:

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

並能夠關閉所有這樣的下拉菜單:

dropdown.close();

我一直在使用帶有inits和public方法的模塊模式一段時間。 不是jQuery插件模式的完全匹配匹配,但是非常可擴展且工作得非常好。 最近剛剛為UMD / CommonJS / AMD /等更新了它。

您可以在此處查看我的入門模板 ,並在此處查看工作示例

為了更好的衡量,這里的完整模板:

/**
 *
 * 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;

});

我想說你想要一個JavaScript類。

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);
}

然后你可以這樣做:

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

插件的一種常見做法是在構造函數中傳遞選項對象。 這樣您就可以優雅地參數化某些行為。 例:

var dropdown = new PluginName({el:'.dropdown',slideInterval:1000, effect:'fade'});

查找javascript原型繼承。

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")

此網站還有令人敬畏的JavaScript設計模式 - http://addyosmani.com/resources/essentialjsdesignpatterns/book/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM