After posting some of this code on Stack Overflow I was told to have a look here and get some feedback.
I am having fun building a light JavaScript framework and have copied this pattern. It works fine, but I like to have some review on it.
The reason that I was directed here is likely the use of CSSStyleDeclaration
. I wonder if that is good practice, or just a dirty shortcut.
var $ = (function() {
function doCSS(prop, val) {
var isSet = Boolean(val),
action = CSSStyleDeclaration.prototype.setProperty,
args = arguments;
if (isSet) {
this.each(function(node) {
action.apply(node.style, args);
});
return this;
} else if (typeof(prop) === 'object') {
this.each(function(node) {
Object.keys(prop).forEach(function(property) {
node.style[property] = prop[property];
});
});
return this;
} else {
return this.nodes[0].style[prop];
}
}
//
return function(selector, context) {
var element = context || window.document;
return {
selector: selector,
nodeList: element.querySelectorAll(selector),
each: function(action) {
[].forEach.call(this.nodeList, function(item, i) {
action(item, i);
});
return this;
},
toString: function() {
return selector;
},
css: function(prop, val) {
return doCSS.call(this, prop, val);
}
};
};
}());
$.extendingFunction = function() {
alert("I am an extending function");
};
$("#string-css").css("background", "seagreen");
$("#object-css").css({
background: "olive",
color: "yellow"
});
document.getElementById("extending")
.addEventListener("click",$.extendingFunction,false);
h1 {
padding: 5px;
}
<h1 id="string-css">CSS String</h1>
<h1 id="object-css">CSS Object</h1>
<button id="extending">call extended function</button>
Comparing function
As far as the CSSStyleDeclaration
goes, I personally am not in favor of it. To be honest, the original was not as dirty as I made by extending it with the option for an object. The following is how I would think it should be.
function doCSS(prop, val) {
if (typeof (prop) === 'string') {
this.each(function(node) {
node.style[prop] = val;
});
}
if (typeof (prop) === 'object') {
this.each(function(node) {
Object.keys(prop).forEach(function(property) {
node.style[property] = prop[property];
});
});
}
return this;
}