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

私はここしばらくの間、init と public メソッドでモジュール パターンを使用してきました。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();

プラグインの一般的な方法の 1 つは、コンストラクターでオプション オブジェクトを渡すことです。このようにして、いくつかの動作をエレガントにパラメータ化できます。例:

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 に答える