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!
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With