vendredi 6 janvier 2017

jQuery object literal or module pattern with jQuery plugins

let's say we have something like this with the jQuery select2 plugin:

$( function() {

    $( '.select2' ).select2( {
        minimumInputLength: 2,
        templateSelection: myTemplateSelection,
            ajax: {
                dataType: 'json',
                cache: true,
                url: myUrl
            }
    } );

    function myTemplateSelection() {
        // code
    }

    function myUrl() {
        // code
    }

} );

But we wanna use an object literal or the module pattern for the jQuery feature and plugin like this:

var myAjax = {

    init: function() {
        $( '.select2' ).select2( {
            minimumInputLength: 2,
            templateSelection: myTemplateSelection,
                ajax: {
                    dataType: 'json',
                    cache: true,
                    url: myUrl
                }
        } );
     },

    myTemplateSelection: function() {
        // code
    },

    myUrl: function() {
        // code
    }
};

$( document ).ready( myAjax.init );

How can we do that?

Sources:

http://ift.tt/1dSy4ti

http://ift.tt/1BBz11o

Aucun commentaire:

Enregistrer un commentaire