Code Monkey home page Code Monkey logo

jquery-factory's Introduction

jQuery Factory

Build Status npm version bower version Codacy Badge Dependency Status

Super simple, lightweight and solid factory of jQuery plugins. It allows to follow classic JavaScript patterns instead of jQuery's while creating plugin.

Features

  • Support all modern browsers (including mobile browsers)
  • Support Internet Explorer 7-8 (needs jQuery 1.8 or older)
  • Support jQuery version from 1.6
  • Support Zepto (needs data module)
  • Around 600 bytes compressed
  • Efficient code re-usage when writing several plugins
  • Support requirejs/webpack and amd
  • Test mode

Install

Bower

bower install --save jquery-factory

Npm

npm install --save jquery-factory

Usage

Usage with requirejs or webpack

var $ = require('jquery')(window),
    newPlugin = require('jquery-factory')($);

Usage in browser

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="/path/to/newPlugin.jquery.js"></script>

Plugin creation $.newPlugin(pluginName, Constr, callback)

Produces new jQuery plugin in $.fn object with Constr function. Factory accepts string pluginName. If plugin with the same name is exists factory throws an error.

pluginName — name of creating plugin. Should not contain name of existing plugins and internal jQuery methods

Constr — constructor Function for new plugin.

callback — callback function (deprecated)

Constructor

Constr takes $element, options and htmlData arguments.

$element contains jQuery oblect of current element

options has any data passed while plugin init

htmlData has value of data-<pluginname> attribute (for example <span data-plugin="myText"></span>).

Methods

By default each created plugin has built-in init, update and destroy methods that could be redefined.

init method should contain event handlers attaching, initial data, adding classes, etc.

update method using for options update and changing instance state. Method will be called if plugin instance was already created on element.

destroy method for final destroying: handlers unattaching and plugin instance removing (using .removeData).

You can append any method by adding it to prototype of constructor function.

Instances

Plugin instance stores with jQuery .data method so you can get it for testing or other purposes.

You can enable test mode by giving callback argument to $.newPlugin. callback accepts plugin instance context and should return true to continue instance attaching or false to prevent it.

To check accessory of $.fn.pluginName use __constr__ property with Constr to check plugin accessory:

$('.element').data(pluginName) instanceof $.fn.pluginName.__constr__

Examples

Empty plugin

Plugin that does nothing:

(function($) {
  var Plugin = function() {}
  $.newPlugin('plugin', Plugin);
})(jQuery);

Usage:

$('.element-set').plugin();

Element and option

Plugin accepts option and attached element. The opt class adding when attaching plugin.

(function($) {
  var Plugin = function($el, opt) {
    this.$el = $el;
    this.opt = opt;
    
    this.$el.addClass(opt);
  }
  $.newPlugin('plugin', Plugin);
})(jQuery);

Usage:

$('.element-set').plugin('some-class');

init, update, destroy methods and events

(function($) {
  var clickHandler = function(e) {
    var self = e.data;
    e.preventDefault();
    // do something
  }
  
  var Plugin = function($el, opt) {
    this.$el = $el;
    this.opt = $.extend({
      text : ''
    }, opt);
    
    this.init();
  }
  
  // init handlers
  Plugin.prototype.init = function() {
    this.$el
      .on('click', this, clickHandler)
      .text(this.opt.text);
  }
  
  // updating text option
  Plugin.prototype.update = function(opt) {
    $.extend(this.opt, opt);
    this.$el.text(this.opt.text);
  }
  
  // destroy method
  Plugin.prototype.destroy = function() {
    this.$el
      .off('click', clickHandler)
      .removeData('plugin');
  }
  
  // custom method
  Plugin.prototype.smartMove = function() {
    this.$el
      .toggleClass('smart-class');
  }
  
  $.newPlugin('plugin', Plugin);
})(jQuery);

Usage:

// creating
$('.element-set').plugin({
  text : 'This is new instance of "plugin"'
});

// updating
$('.element-set').plugin('update', {
  text : 'blah!'
});

// updating (other way)
$('.element-set').plugin({
  text : 'Blah-blah!'
});

// call custom method
$('.element-set').plugin('smartMove');

// destroying
$('.element-set').plugin('destroy');

More examples available in tests

Todo

  • Create plugin instances with Object.create (will loose compatibility with old browsers)
  • More tests
  • More examples
  • Adapt (maybe fork?) for BEM development process
  • Сompatibility tests with Zepto

Contributing

You are welcomed to improve this small piece of software :)

Author

Thanks to

jquery-factory's People

Contributors

asg-3d avatar peremenov avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

asg-3d klond90

jquery-factory's Issues

Добавить проверку: был ли плагин уже инициализирован?

Можно ли добавить в фабрику проверку, был этот плагин уже инициализирован или нет?
Сейчас приходится писать так:

// --- Init plugin ---
Plugin.prototype.init = function() {
    var self = this;

    if (self.$element.data('plugin') == 'initialised') {
        return;
    } else {
        self.$element.data('plugin', 'initialised');
    }
};

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.