querySelectorAll with custom library

I have this code:

(function() {

var base = function (elem) {

    var elements = document.querySelectorAll(elem);

    return {
        elems: elements[0],
        on: function (evt, func) {
            if(this.elems) this.elems.addEventListener(evt, func, false);
            return this;
        }
    };
};


window.base = window._ = base;

})();

And I can do this:

_('form').on('submit', uploadImage);

But if i do:

_('form').appendChild(input);

i get an error: Object #<Object> has no method 'appendChild'

So how can i use _('element') with native functions and still make it work with the methods in my object?

Answers


Give your object an .appendChild function that calls the .appendChild on the element.

(function() {

    var base = function (elem) {

        var elements = document.querySelectorAll(elem);

        return {
            elems: elements[0],
            on: function (evt, func) {
                if(this.elems) this.elems.addEventListener(evt, func, false);
                return this;
            },
            appendChild: function(el) {
                this.elems.appendChild(el);
                return this;
        };
    };


    window.base = window._ = base;

})();

Side note. If you're only interested in the first element returned from querySelectorAll, you can use querySelector instead.

return {
    elems: document.querySelector(elem),
    on: function (evt, func) {
      // ...

I think you can do this with prototype (not recommended):

// Prototype.js style
var Base = function (selector) {
    return document.querySelector(selector);
};

Element.prototype.on = function (e, f) {
    this.addEventListener(e, f, false);
    return this;
};

elp = Base('#result');
elp.on('click', function () {
    console.log(this);
});

elp instanceof Element; // true
elp.innerHTML; // text

Or with an object wrapper:

// jQuery style
var Base = function (selector) {
    this[0] = document.querySelector(selector);
    return this;
};

Base.prototype.on = function (e, f) {
    this[0].addEventListener(e, f, false);
    return this;
};

elj = new Base('#result'); // internal new called in jQuery
elj.on('click', function () {
    console.log(this);
});

elj instanceof Base; // true
elj[0] instanceof Element; //true
elj[0].innerHTML; // text

Need Your Help

org.mule.routing.ExpressionSplitter: Splitter only returned a single result. If this is not expected, please check your split expression

mule

I have created a custom java component which reads the JMS Messages in "for loop", removes the duplicate messages based on specific pattern and adds the redundant messages to array list and return ...

How do I use method overriding in this case?

c# method-overriding

So this is my class and I just learned a little bit about inheritance. I heard about overriding methods but how do I do it in this case?