Thursday, March 15, 2012

Inheritance in Javascript using jQuery

Here is a small JS code snippet, that allows you to create class trees with almost any inheritance complexity.
NB: Uses jQuery
createClass : function (a, b) {
    var c = function() {
        $(this.__constructor.apply(this,arguments));
    },e='prototype',f;
    if ($.isFunction(a)) {
        (f = function() { })[e] = a[e];
        ((c[e] = new f()).constructor = c).parentClass = a[e];
        a = b;
    }
    $.extend(c[e],a);
    return c;
}
Basic usage:
ClassA = createClass({
    __constructor : function() {
        
    }
});
ClassB = createClass(ClassA,{
    __constructor : function() {
        ClassB.parentClass.__constructor.apply(this,arguments);

    }
});
Inheritance power demonstration:
ClassA = createClass({
    __constructor : function() {
        
    },
    hello_world : function() {
        alert('ClassA says Hello World');
    }
});

ClassB = createClass(ClassA,{
    __constructor : function() {
        ClassB.parentClass.__constructor.apply(this,arguments);
        this.hello_world();
    },
    hello_world : function() {
        ClassB.parentClass.hello_world.apply(this,arguments);
        alert('ClassB says Hello World');
    }
});
This example will give you two alerts in the following order:
  • 1. 'ClassB says Hello World'
  • 2. 'ClassA says Hello World'
Important notes:
"__constructor" is just name, that can be replace with anything you'd like, I'm usually using "init"
"parentClass" also replaceable with any other keywords you'd like.


Happy using!

Friday, March 2, 2012

jQuery.linqSelect and jQuery.datas()

We all know that jQuery has "data" method, but when dealing with more than one DOM element, I'd like to have method called "datas", which would return an array of all "data" calls for each element in jQuery selection.


After some coding, here is a solution I've finally came up with:

$.fn.linqSelect = function(n, fn) {
    var vs = [], f, t, i, v, r, a = $.isArray(n);
    $(this).each(function() {
        if (f = (t = $(this))[fn]) {
            if (a && (r = { })) for (i in n) r[v = n[i]] = f.apply(t, [v]);
            else r = n!=null ? f.apply(t, [n]) : f.apply(t);
            vs.push(r);
        }
    });
    return vs;
};

Possible usages:
$("a").linqSelect('href','attr');
Will return an array of all A's href attributes
$("input:radio[data-name][data-value]").linqSelect(['name','value'] ,'data');
Will return an array of objects {name:...,value:...} filled with corresponding data


Also one shortcut function :
$.fn.linqSelectData = function(n) {
    return this.linqSelect(n, 'data');
};
Usage:
$("input:radio[data-name][data-value]").linqSelectData(["id", "value", "sid"]);
That idea mainly shows the direction of how to implement other linq-like functions