How to create a plugin for jQuery's $ () function

5

I noticed that you can create plugins in various jQuery functions like AJAX, CSS (using cssHooks ), animate , create new functions, among others. But I thought if you could create a plugin for the service call function, for example:

$ ('26/08/1966')

As an example the plugin could return a string with the most detailed date to use with the jQuery (html, css,

Understand as a way to teach jQuery what to do with the string indicated at the beginning.

I do not know if this is possible, I searched and did not find anything related (I do not know if I researched it right) and it would be interesting because it could make it easier to use a plugin I'm doing.     

asked by anonymous 07.05.2014 / 00:13

3 answers

3

Background

jQuery specializes in dealing with DOM elements. When you do something like:

var x = $("seletor")

It creates an object that contains - among other things - a list with zero or more elements. Other ways to create this object:

var a = document.getElementById("a");
var b = document.getElementById("b");
var c = document.getElementById("c");
var x = $([a, b, c]); // Lista com 3 elementos
var x = $(a);         // Lista com 1 elemento
var x = $();          // Lista com 0 elemento

var x = $("<div><span>Teste</span></div>"); // Cria um elemento e põe na lista
var x = $("<p>A</p><p>B</p><p>C</p>");      // Idem, para mais de um elemento

All functions of the "jQuery object" then operate on DOM element lists . You can create other user-defined functions, but they are also expected to act on DOM element lists:

$.fn.minhaFuncao = function() {
    // Aqui "this" é um objeto jQuery
    // Pode-se fazer isso:
    return this[0].value; // Retorna o valor do primeiro elemento
    // Ou isso:
    return this.each(function() { 
        this.value = 10; 
    }); // Faz todos elementos terem o valor 10, e retorna o próprio objeto (pra chaining)
};

Response

Using jQuery in arbitrary object lists is tricky as it would blend unsupported data types. If you wanted to deal with date lists (or worse: single dates) all of the original jQuery functions could be called on those dates (causing errors as they are distinct types) and in the same way the new functions you created could also be called in the DOM element list (idem).

Mixing both, so not a good idea ... I do not know a generalized solution to doing this for "type A lists", but there are libraries like Underscore.js that use a jQuery-like concept (make wrap in an object to introduce its own functions, even with chaining) to accomplish its specific purposes. >

If the question is to add methods to individual elements of a type, just move your prototype:

Date.prototype.formatarData = function() {
    // "this" aqui é um objeto Date
}

var agora = new Date();
agora.formatarData(); // Chama seu método num objeto com a data atual

There are some who consider this a bad practice (eg, myself) for "polluting the namespace", but used as moderation and care may be a good option ...

    
07.05.2014 / 22:08
2

The syntax for creating a new plugin that is in the jQuery documentation is:

$.fn.esverdear = function() {
    this.css( "color", "green" );
};

$("a").esverdear(); // Muda a cor de todos os elementos para verde.

To work a URL could, for example, do as I put it down. Note that returning a jQuery object (i.e. with wrapper $() ) is important to be able to associate other methods like .each() in the example:

var url = 'http://server/path/program?foo=bar&animal=gato';

$.fn.abrirURL = function (url) {
    var regex = /[?&;](.+?)=([^&;]+)/g;
    var match;
    params = [];
    if (url) {
        while (match = regex.exec(url)) {
            var param = {};
            param[match[1]] = decodeURIComponent(match[2]);
            params.push(param);
        }
        return $(params);
    }
};

$.fn.abrirURL(url).each(function () {
    console.log(this)
});

// Isto vai dar:
// Object {foo: "bar"} 
// Object {animal: "gato"} 

Example

    
07.05.2014 / 00:43
1

If I understand correctly, you are wanting to create a function to format a date with JQuery . If so, you can do this:

(function( $ ){
   $.fn.formatadata = function() {          
      //formata a data
   }; 
})( jQuery );

$('.data').formatadata();

You can read more about How to Create a Basic Plugin

    
07.05.2014 / 00:42