Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a javascript plugin without jQuery

Writing plugins with jQuery is relatively easy, just use $.fn and you're on your way. Like so:

$.fn.analyse = function() {
...
}

But what if you're not able to use jQuery?

Let's say I want to be able to use the following code:

document.querySelector("#mydiv").analyse();

I could go about it like this:

Object.prototype.analyse = function() {
...
}

But from what I understand it is frowned upon!

like image 326
Björn Andersson Avatar asked Feb 02 '13 21:02

Björn Andersson


2 Answers

Here's something to get you started:

var proto_methods = {
    analyse: function() {
        var node = this.node;

        // ...
    }
}, wrap, _wrap;

_wrap = function(selector) { this.node = document.querySelector(selector); };
_wrap.prototype = proto_methods;

wrap = function(selector) {
    return new _wrap(selector);
};

Use it like this:

wrap("#mydiv").analyse();

Use this if you want to add more plugins (and it's a little more object-oriented):

var pack = {
    binder: [{}]
};

pack.query_bind = function( bound ) {
    if (bound) pack.binder[1] = bound;
};

pack.fn = function( attributes ) {
    for (var i in attributes) pack.binder[0][i] = attributes[i];
};

var _wrap = function(selector) {
    this.node = /^(#|.)\w+/.test(selector) ? pack.binder[1](selector) : {};
};

_wrap.prototype = pack.binder[0];

var wrap = function(selector) {
    pack.query_bind(document.querySelector.bind(document));
    return new _wrap(selector);
};

wrap.fn = pack.fn;

wrap.fn({
    cool: function() {},
    nice: function() {}
});

wrap('#mydiv').cool();

You can call wrap.fn at any time and the prototype will be updated.

However, note that this is not a true replacement for jQuery as there are a lot of things that I have not included in this code. The wrap function is not as advanced and useful as jQuery's $ in many ways.

I hope this helps.

like image 101
David G Avatar answered Nov 12 '22 16:11

David G


Just wrote boilerplate. It have no own selector logic because It's designed for library on top of D3.js which already have own selector engine. https://gist.github.com/turboMaCk/34bde8e744f5921be0c4

like image 36
Marek Fajkus Avatar answered Nov 12 '22 17:11

Marek Fajkus