2013-01-16 107 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和公共方法一段時間了。不是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; 

});