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

Asked

Viewed 1,664 times

5

I noticed that you can create plugins in various jQuery functions like AJAX, CSS (using the cssHooks), animate, create new functions, among others. But I wondered if it is possible to 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 jQuery(html, css, each functions).

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

I don’t know if this is possible, I searched and found nothing related (I don’t know if I researched right) and it would be interesting why I could facilitate the use of a plugin I’m doing.

  • 2

    Can you explain better what you intend to do?

  • 3

    I think you can solve your problem differently. It’s not quite there... I mean: what you intend to do can probably be achieved without the need to "create a plugin for the service call function", as you say.

  • the string that went in the call of jQuery would be a url and the plugin also creates functions to mess with a cloud storage service that I created.

  • At least I thought it would return the initial string but in some tests did not work very well, the value always back Undefined

  • 1

    @Iagobruno It turns out that jQuery plays $(string) like using a selector, it has no way of differentiating a string whose content is a string date whose content is a selector (ok, in this case it could, but because the syntaxes are sufficiently distinct). That would be a case of DWIM, which in my opinion is a bad practice [in this context at least]. An example are the spreadsheets, which deal with 1 as a number, 1/2 as a fraction and 1/2/3 how to date! Types in a programming language have to be unmistakable.

  • no one understood that the date format was just an example =p. But @mgibsonbr but if I were to do it I would try to use the jQuery context, for example: $('12/08/2013', 'date'). getDay(). But thank you for the reply/comment.

Show 1 more comment

3 answers

3

Background

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

var x = $("seletor")

It creates an object that contains - among other things - a list of 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 lists of FOD elements. Other user-defined functions can be created, but they are expected to also 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)
};

Answer

Using jQuery in arbitrary object lists is complicated, as it would mix incompatible data types. If you wanted to deal with date lists (or worse: isolated dates) all original jQuery functions could be called on those dates (causing errors as they are different types) and similarly the new functions you create could also be called in the DOM element lists (idem).

Mix the two, so it’s not a good idea... I don’t know a generalized solution to do this for "type A lists," but there are libraries like Underscore.js using a concept similar to that of jQuery (do wrap on an object to introduce its own functions, including with chaining) to accomplish its specific purposes.

If the question is adding methods to individual elements of a kind, just touch 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

Some consider this bad practice (myself, for example) by "polluting the namespace", but used as moderation and care can be a good option...

  • 2

    I think the author of the question misunderstood the use of JQuery or exemplified in the wrong way. jQuery is to interact with HTML, probably it is wanting something like $('.data').formatarData();, otherwise it makes no sense to use Jquery

  • I understand about jQuery '-', the date format was just an example. Looking at the jQuery code I couldn’t find any part that made it possible to do this, so there is no solution to my question. o/

  • Yes, jQuery plays especially with DOM elements, but that would be a way to "teach" jQuery what to do with the new format, but it doesn’t have the same.

2

A syntax to create a new plugin that is in the documentation so jQuery 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 below. Note that return a jQuery object (i.e. with wrapper $()) is important to be able to associate other methods such as .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

  • But in this case, what is the advantage of using $.fn.abrirURL about, say, just function abrirURL? If your function does not operate in DOM element lists, it makes no sense to write it as a jQuery pro plugin. See my answer for more details.

  • 2

    @mgibsonbr agree with you. I tried to answer the question by showing how to create a plugin. In case it is to work non-dom elements I agree that jQuery is not the most indicated. That’s where for example the Mootools shines... +1 for your answer

  • 1

    I didn’t know Mootools was good for it, so I guess I’ll take the time to learn how to use it then. I usually use Underscore.js - for its higher-level functions when dealing with lists and objects.

1

If I understand correctly, you are wanting to create a function to format a date through JQuery. If that’s it, you can do it like this:

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

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

You can read more about on How to Create a Basic Plugin

  • If the date to be formatted is in an DOM element, then yes, your answer is correct. But I think that’s not quite what the OP is looking for, it seems to me that the idea is to use jQuery to manipulate other types of data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.