Giter Club home page Giter Club logo

jquery-patterns's Introduction

jQuery Boilerplate Build Status Bower Version

A jump-start for jQuery plugins development

So, you've tried your hand at writing jQuery plugins and you're comfortable putting together something that probably works. Awesome! Thing is, you think there might be better ways you could be writing them - you've seen them done a number of different ways in the wild, but aren't really sure what the differences between these patterns are or how to get started with them.

This project won't seek to provide a perfect solution to every possible pattern, but will attempt to cover a simple template for beginners and above. By using a basic defaults object, simple constructor for assigning the element to work with and extending options with defaults and a lightweight wrapper around the constructor to avoid issues with multiple instantiations.

Usage

  1. Include jQuery:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  2. Include plugin's code:

    <script src="dist/jquery.boilerplate.min.js"></script>
  3. Call the plugin:

    $("#element").defaultPluginName({
    	propertyName: "a custom value"
    });

Structure

The basic structure of the project is given in the following way:

├── demo/
│   └── index.html
├── dist/
│   ├── jquery.boilerplate.js
│   └── jquery.boilerplate.min.js
├── src/
│   ├── jquery.boilerplate.coffee
│   └── jquery.boilerplate.js
├── .editorconfig
├── .gitignore
├── .jshintrc
├── .travis.yml
├── Gruntfile.js
└── package.json

Contains a simple HTML file to demonstrate your plugin.

This is where the generated files are stored once Grunt runs.

Contains the files responsible for your plugin, you can choose between JavaScript or CoffeeScript.

This file is for unifying the coding style for different editors and IDEs.

Check editorconfig.org if you haven't heard about this project yet.

List of files that we don't want Git to track.

Check this Git Ignoring Files Guide for more details.

List of rules used by JSHint to detect errors and potential problems in JavaScript.

Check jshint.com if you haven't heard about this project yet.

Definitions for continous integration using Travis.

Check travis-ci.org if you haven't heard about this project yet.

Contains all automated tasks using Grunt.

Check gruntjs.com if you haven't heard about this project yet.

Specify all dependencies loaded via Node.JS.

Check NPM for more details.

Guides

How did we get here?

Have you got in this repo and still not sure about using this boilerplate?

Well, extending jQuery with plugins and methods is very powerful and can save you and your peers a lot of development time by abstracting your most clever functions into plugins.

This awesome guide, adapted from jQuery Plugins/Authoring, will outline the basics, best practices, and common pitfalls to watch out for as you begin writing your plugin.

How to publish plugins?

Also, check our guide on How to publish a plugin in jQuery Plugin Registry!

Note: The jQuery Plugin Registry is in read-only mode. New plugin releases will not be processed. jQuery recommends moving to npm, using "jquery-plugin" as the keyword in your package.json. See how to publish into npm registry.

Team

jQuery Boilerplate was made with love by these guys and a bunch of awesome contributors.

Zeno Rocha | Addy Osmani | Helder Santana --- | --- | --- | --- | --- | --- | --- Zeno Rocha | Addy Osmani | Helder Santana

Contributing

Check CONTRIBUTING.md for more information.

History

Check Releases for detailed changelog.

License

MIT License © Zeno Rocha

jquery-patterns's People

Contributors

addyosmani avatar camskene avatar collin-garvey avatar kahlil avatar leevigraham avatar markdalgleish avatar patromo avatar sindresorhus avatar toddmotto avatar zenorocha avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-patterns's Issues

Basic pattern breaks chainability

Is it a good practice to break the second plugin instance if we call it like this?

$(selector).defaultPluginName({
    start: 13,
    end: 37
}).defaultPluginName({
    start: 37,
    end: 42
});

It will not work since we allow the plugin only to be instantiated once per element. But to remove the if statement in our plugin definition is even not the best idea, or?

Discussion

Just chiming in here, going to post some thoughts later today.

publish event works only on page load

If we publish any notification based on some click event then that event is not sub scribed. if you invoke the below method based on some button click event then it does not perform the actions in subscribe event.

$("#testPlugin").testSubscribe().trigger("eventPublished");

But if we perform the below step on page load then it works.

$("#testPlugin").testSubscribe();
$("#testPlugin").testSubscribe().trigger("eventPublished");

this.[functionOne] is not a function

Hi, could someone explain where I am going wrong. I'm trying to use the jQuery boilerplate but having trouble when adding functions and calling them:

/*!
 * jQuery lightweight plugin boilerplate
 * Original author: @ajpiano
 * Further changes, comments: @addyosmani
 * Licensed under the MIT license
 */

// the semi-colon before the function invocation is a safety
// net against concatenated scripts and/or other plugins
// that are not closed properly.
;(function ( $, window, document, undefined ) {

    // undefined is used here as the undefined global
    // variable in ECMAScript 3 and is mutable (i.e. it can
    // be changed by someone else). undefined isn't really
    // being passed in so we can ensure that its value is
    // truly undefined. In ES5, undefined can no longer be
    // modified.

    // window and document are passed through as local
    // variables rather than as globals, because this (slightly)
    // quickens the resolution process and can be more
    // efficiently minified (especially when both are
    // regularly referenced in your plugin).

    // Create the defaults once
    var pluginName = "defaultPluginName",
        defaults = {
            propertyName: "value"
        };

    // The actual plugin constructor
    function Plugin( element, options ) {
        this.element = element;

        // jQuery has an extend method that merges the
        // contents of two or more objects, storing the
        // result in the first object. The first object
        // is generally empty because we don't want to alter
        // the default options for future instances of the plugin
        this.options = $.extend( {}, defaults, options) ;

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    Plugin.prototype = {
        
        init: function() {
            // Place initialization logic here
            // You already have access to the DOM element and
            // the options via the instance, e.g. this.element
            // and this.options
            // you can add more functions like the one below and 
            // call them like so: this.yourOtherFunction(this.element, this.options).

            $(this.element).each(function() {
                console.log('Main function');

                this.functionOne(this.element, this.options);
            });
        }, 

        functionOne: function(el, options) {
            console.log('functionOne');
            
            this.functionTwo(el, options);
        },

        functionTwo: function(el, options) {
            console.log('functionTwo');
        }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function ( options ) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                $.data(this, 'plugin_' + pluginName,
                new Plugin( this, options ));
            }
        });
    }

})( jQuery, window, document );

This simple calling of functions results in the following console log:

Main function

TypeError: this.functionOne is not a function
this.functionOne(this.element, this.options);

Did I miss something? Reading the comments in the script, I think I'm calling the functions correctly?

Thanks!

Adding Ability to Call $. defaultPluginName()

Hi,

I was hoping this template could be updated so that it can support the ability to be called as $. defaultPluginName() so it can return a value (string, object, boolean) along with $(selector).defaultPluginName() so it can return a chain able object.

I'm actually trying to figure out how it's done and so for unsuccessful. I'll continue to look up how it's done to go along with this boilerplate.

Exposing defaults as a property of $.fn.pluginName

I was about to apply your basic plugin boilerplate to my plugins as I think in general it's neater than what I've been doing, but there is one thing I don't like; namely that the defaults are not exposed publically so that a developer can change the default settings for the plugin (eg if a plugin defaults to autoplay: false, but on the developer's site most instances use autoplay:true it makes sense for them to over-ride the default globally). Of course, the developer coudl go in and directly edit the plugin, but I never like doing this as it's not obvious to future developers that they can't just overwrite the plugin with updated versions from the plutgin's author.

I think this would need to be done by getting rid of the defaults variable and using $.fn[pluginName].defaults instead.

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.