2013-01-16 7 views
8

さて、我々はすべてのjQueryのプラグインを作成する方法を知っている:http://docs.jquery.com/Plugins/AuthoringバニラJSプラグインテンプレート

は、誰かが方法およびデフォルト設定で純粋なJavascriptのテンプレートプラグインについて助言することはできますか?私はそれが単一のノードとし、ノード・アレイ(querySelectorAll)で動作するようにしたい

このような何か:

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

そして、このようにそれを呼び出す:

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

このようなすべてのドロップダウンを閉じることができる:

dropdown.close(); 
+1

ピュアJavascriptが 'selectors'を持っていない、それはjQueryのの機能です。 DOMノードを渡す必要があります。それは受け入れられますか? – Nucleon

+2

私たちは 'querySelector'を使用することができます – bravedick

+0

はい、しかし、古いブラウザではquerySelectorが利用できないことに注意してください:http://caniuse.com/queryselector – miguelcobain

答えて

3

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/

8

私はあなたが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'}); 
16

私はinitsとpublicメソッドのモジュールパターンを少しずつ使っています。正確なjQueryプラグインパターンのマッチはありませんが、かなり拡張性があり、とてもうまく動作します。ちょうど最近UMD/CommonJS/AMD /などのためにそれを更新しました。

あなたはチェックアウトmy starter template hereを確認し、working example 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; 

}); 
関連する問題