10

好的,我们都知道如何编写 jQuery 插件:http ://docs.jquery.com/Plugins/Authoring

有人可以就带有方法和默认设置的纯 Javascript模板插件提供建议吗?

我想让它与单个节点和节点数组(querySelectorAll)一起工作

像这样的东西:

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

并这样称呼它:

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

并且能够像这样关闭所有下拉菜单:

dropdown.close();
4

3 回答 3

21

一段时间以来,我一直在使用带有 inits 和公共方法的模块模式。不是 jQuery 插件模式的完全匹配,但相当可扩展并且工作得非常好。刚刚为 UMD/CommonJS/AMD/etc 更新了它。

您可以在此处查看我的入门模板,并在此处查看一个工作示例

为了更好地衡量,完整的模板在这里:

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

});
于 2014-06-18T21:13:27.047 回答
9

我会说你想要一个 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'});
于 2013-01-16T15:49:01.643 回答
4

查找 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/

于 2013-01-16T15:46:48.920 回答