/ Gists

Gists

On gists

Multiple promises via argument

jQuery

how-to-solve.js #

function queryPartners(promise){
    /* Query Partners */
    ... // The code for however we are querying and returning the data.

    /* Query is complete, resolve promise */
    promise.resolve();
    return promise;
}
function queryUsers(promise){
    /* Query Users*/
    ... // The code for however we are querying and returning the data.

    /* Query is complete, resolve promise */
    promise.resolve();
    return promise;
}
function processInfo(promise){
    /* Process Data */
    ... // The code for however we are processing the info.

    /* Processing is complete, resolve promise */
    promise.resolve();
    return promise;
}


// TO ONE

function getInfo(){
    /* Initialize Deferred Promises for each function */
    var a = $.Deferred();
    var b = $.Deferred();
    var c = $.Deferred();

    /* Query Partners, supply the promise (a) */
    a = queryPartners(a);
    /* Query Users, supply the promise (b) */
    b = queryUsers(b);

    /* .when() both queries are .done(), run processInfo() */
    $.when(a,b).done(function(){
        /* Process Info from Users, supply promise */
        c = processInfo(c);
    });

    return c;
}

On gists

Recontruct nav cache

AW

reconcstruct-nav-cache.sql #

TRUNCATE navigation_cache;

INSERT INTO navigation_cache 
(navigation_id, language_id, path, id_path)
(
    SELECT navigation_id, language_id, NavigationPath(navigation_id, language_id, title), CONCAT(NavigationIdPath(navigation_id, language_id), "/")
    FROM navigation_lang
);

On gists

Sum plugin

jQuery jQuery-plugins

sum.js #

function( $ ){
   $.fn.sum=function () {
	var sum=0;
		$(this).each(function(index, element){
			sum += parseFloat($(element).val());
		});
	return sum;
    }; 
})( jQuery );
//Call $('.abcd').sum();

On gists

Remove object from array of objects in Javascript

JavaScript

splice-object-array.js #

// source: http://stackoverflow.com/questions/16491758/remove-objects-from-array-by-object-property

// we have an array of objects, we want to remove one object using only the id property
var apps = [{id:34,name:'My App',another:'thing'},{id:37,name:'My New App',another:'things'}];

// get index of object with id:37
var removeIndex = apps.map(function(item) { return item.id; }).indexOf(37);

// remove object
apps.splice(removeIndex, 1);

On gists

Basic jQuery Plugin using the Module Pattern

Plugin patterns jQuery-plugins

plugin.js #

/**
 *  A basic jQuery plugin using the Module Pattern
 * *
 *  @author      Sam Deering
 *  @copyright   Copyright (c) 2012 jQuery4u
 *  @license     http://jquery4u.com/license/
 *  @since       Version 1.0
 *
 */

!function(exports, $, undefined)
{
    var Plugin = function()
    {

        /*-------- PLUGIN VARS ------------------------------------------------------------*/

        var priv = {}, // private API

            Plugin = {}, // public API

            // Plugin defaults
            defaults = {
                id : '',
                name : '',
                url : ''
            };

        /*-------- PRIVATE METHODS --------------------------------------------------------*/

        priv.options = {}; //private options

        priv.method1 = function()
        {
            console.log('Private method 1 called...');
            $('#videos').append(''+this.options.name+'');
            priv.method2(this.options);
        };

        priv.method2 = function()
        {
            console.log('Private method 2 called...');
            $('#'+priv.options.id).append(''+this.options.url+''); // append title
            $('#'+priv.options.id).append(''); //append video
        };

        /*-------- PUBLIC METHODS ----------------------------------------------------------*/

        Plugin.method1 = function()
        {
            console.log('Public method 1 called...');
            console.log(Plugin);

            //options called in public methods must access through the priv obj
            console.dir(priv.options);
        };

        Plugin.method2 = function()
        {
            console.log('Public method 2 called...');
            console.log(Plugin);
        };

        // Public initialization
        Plugin.init = function(options)
        {
            console.log('new plugin initialization...');
            $.extend(priv.options, defaults, options);
            priv.method1();
            return Plugin;
        }

        // Return the Public API (Plugin) we want
        // to expose
        console.log('new plugin object created...');
        return Plugin;
    }

    exports.Plugin = Plugin;

}(this, jQuery);


jQuery(document).ready( function()
{
    console.log('doc rdy');

    // EXAMPLE OF CREATING PLUGIN OBJECTS WITH CUSTOM SETTINGS

    console.log('--------------------------------------------');

    var myPlugin1 = new Plugin;
    myPlugin1.init(
    {
        /* custom options */
        id : 'vid01',
        name : 'Video 1',
        url : 'http://www.youtube.com/embed/dXo0LextZTU?rel=0'
    });

    //call to public methods
    myPlugin1.method1();
    myPlugin1.method2();

    console.log('--------------------------------------------');

    var myPlugin2 = new Plugin;
    myPlugin2.init(
    {
        /* custom options */
        id : 'vid02',
        name : 'Video 2',
        url : 'http://www.youtube.com/embed/nPMAUW-4lNY?rel=0'
    });

    //call to public methods
    myPlugin2.method1();
    myPlugin2.method2();

    // console.log('--------------------------------------------');

});

On gists

jQuery plugin skeleton

Plugin patterns jQuery-plugins

skeleton.js #

/*!
 * AW {{PROJECTNAME}}
 *
 *
 * @author  {{firstname lastname}} <{{email}}>
 * @version  1.0.0
 *
 */

 /*
    {{PLUGIN}} => realname of project, eg: awBestPlugin
 */

;(function() {
    'use strict';

    function {{PLUGIN}}(element, options) {
        this.self  = $(element);
        this.settings   = $.extend(true, {}, $.fn.{{PLUGIN}}.defaults, options);

    }


    {{PLUGIN}}.prototype = {
        
        /* PRIVATE METHODS */
        _create: function() { 
           
        }

  
        /* PUBLIC METHODS */
      
    };


    (function ($) {
        $.fn.{{PLUGIN}} = function(options) {
            var
            args   = Array.prototype.slice.call(arguments, 1),
            method = {{PLUGIN}}.prototype[options];

            
            return this.each(function() {
                var self     = $(this);
                var instance = self.data('{{PLUGIN}}');

                if (!instance) {
                    instance = new {{PLUGIN}}(this, options);
                    instance._create();
                    self.data('{{PLUGIN}}', instance);
                }

                if (method && options.substring(0, 1) == '_') 
                    $.error('Cannot use private method "' + options + '" outside of object');
                
                if (method) {
                    method.apply(instance, args);
                } else if (options && typeof options !== 'object') {
                    $.error('Method "' + options + '" not found.');
                }
            });
        };

        $.fn.{{PLUGIN}}.defaults = {
 
        };
    })(jQuery);
})();

On gists

jQuery: plugin pattern

Plugin patterns jQuery jQuery-plugins

jquery.plugin_pattern.js #

/*
 *  Project:
 *  Description:
 *  Author:
 *  License:
 */

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

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

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

    var pluginName = "linkColor",
    // the name of using in .data()
        dataPlugin = "plugin_" + pluginName,
    // default options
        defaults = {
            color: "black"
        };

    var privateMethod = function () {
        console.log("private method");
    };

    // The actual plugin constructor
    var Plugin = function ( element ) {
        /*
         * Plugin instantiation
         */
        this.options = $.extend( {}, defaults );
    };

    Plugin.prototype = {

        init: function ( options ) {

            // extend options ( http://api.jquery.com/jQuery.extend/ )
            $.extend( this.options, options );

            /*
             * Place initialization logic here
             */
            this.element.css( 'color', 'red' );
        },

        destroy: function () {
            // unset Plugin data instance
            this.element.data( dataPlugin, null );
        },

        // public get method
        href: function () {
            return this.element.attr( 'href' );
        },

        // public chaining method
        changeBG: function ( color = null ) {
            color = color || this.options['color'];
            return this.element.each(function () {
                // .css() doesn't need .each(), here just for example
                $(this).css( 'background', color );
            });
        }
    }

    /*
     * Plugin wrapper, preventing against multiple instantiations and
     * allowing any public function to be called via the jQuery plugin,
     * e.g. $(element).pluginName('functionName', arg1, arg2, ...)
     */
    $.fn[ pluginName ] = function ( arg ) {

        var args, instance;

        // only allow the plugin to be instantiated once
        if (!( this.data( dataPlugin ) instanceof Plugin )) {

            // if no instance, create one
            this.data( dataPlugin, new Plugin( this ) );
        }

        instance = this.data( dataPlugin );

        instance.element = this;

        // Is the first parameter an object (arg), or was omitted,
        // call Plugin.init( arg )
        if (typeof arg === 'undefined' || typeof arg === 'object') {

            if ( typeof instance['init'] === 'function' ) {
                instance.init( arg );
            }

        // checks that the requested public method exists
        } else if ( typeof arg === 'string' && typeof instance[arg] === 'function' ) {

            // copy arguments & remove function name
            args = Array.prototype.slice.call( arguments, 1 );

            // call the method
            return instance[arg].apply( instance, args );

        } else {

            $.error('Method ' + arg + ' does not exist on jQuery.' + pluginName);

        }
    };

}(jQuery, window, document));

On gists

JS: patterns Singleton

JavaScript-OOP JavaScript Plugin patterns

singleton.js #

var mySingleton = (function () {

    // Instance stores a reference to the Singleton
    var instance;

    function init() {

        // Singleton

        // Private methods and variables
        function privateMethod(){
            console.log( "I am private" );
        }

        var privateVariable = "Im also private";

        return {

            // Public methods and variables
            publicMethod: function () {
                console.log( "The public can see me!" );
            },

            publicProperty: "I am also public"
        };
    }

    return {

    // Get the Singleton instance if one exists
    // or create one if it doesn't
    getInstance: function () {

        if ( !instance ) {
            instance = init();
        }

        return instance;
    }

    };

})();

On gists

Visual Studio Code Settings Sync Gist

Visual Studio Code

cloudSettings #

{"lastUpload":"2020-03-27T08:26:37.234Z","extensionVersion":"v3.4.3"}

On gists

Events, store data out of DOM (own object)

jQuery

good-practice.html #

<script>
  var model = {
  first: "",
  last: "",
};

function update(key, val) {
  model[key] = val;
}

function onInput(e) {
  var input = $(e.target);
  var key = input.attr('name');
  var val = input.val().trim();
  update(key, val);
}

function onSubmit(e) {
  e.preventDefault();
  $.post('/foo', model)
    .done(onSuccess)
    .fail(onError);
}

var form = $('#myform');
form.on('input', onInput);
form.on('submit' onSubmit);

</script>