Developer Snippet - Capturing Console.Log
Nobody is perfect. I’ve left a console.log() in countless live deployments, and I will probably do it again. While it does speak volumes about my attention to detail after a long day of coding, there is a way to prevent it. It’s easy enough to detect when the console object doesn’t exist - so you can just do the following.
if (!window.console) {
window.console = {};
window.console.log = function() {
return false;
};
}
The only thing is that, well, I’m not particularly fond of this snippet. While it’s a good development tool for quick and easy testing in Internet Explorer and other browsers that do not support console logging, I don’t recommend you push this live. Not only does it promote lazy coding habits and deployment protocols, but it also encourages developers to litter the end user’s console with statements. On the other hand it does lend itself to better bug tracking and support on a live site. This is best determined on a case-by-case situation.
I created a GitHub gist for better readability and comment tracking. I wish Tumblr would allow iframe embedding or at least code formatting.
JavaScript Prototype “Class” Manager
I thought I’d share an amazing little snippet of code I picked up months ago, and that I haven’t been able to find anywhere else since. My latest Workflow project I’ve been blogging about forced me to finally teach myself OO JavaScript. It’s been stressful, but rewarding.
Creating object oriented code was pretty cool, but storing each object in an array (and subsequently performing functions on this array) is a completely different matter. After some chatting on the #javascript channel on freenode, someone gave me this absolute nugget:
/* === MANAGER CLASS === */
var Manager = function(cons) {
this.cons = cons;
this.objs = [];
};
Manager.prototype.create = function(args) {
var inst = new this.cons(args)
this.objs.push(inst);
return inst;
};
Manager.prototype.all = function() {
return this.objs;
};
Manager.prototype.findBy = function(p, v) {
for(var i = 0, len = this.objs.length; i < len; i++) {
if(this.objs[i][p] === v) {
return this.objs[i];
}
}
};
Manager.prototype.remove = function(o) {
for(var i = 0, len = this.objs.length; i < len; i++) {
if(this.objs[i].id === o.id) {
this.objs.splice(i,1);
i = this.objs.length;
}
}
};
If you have an object you’ve created, such as the following:
var Person = function() {
this.init();
}
It just becomes a matter of creating a new instance of the manager “class” and specifying the constructor:
var AddressBook = new Manager(Person);
AddressBook.create({FirstName: “Bob”});
While plenty of critics are going to rush to the comments section describing what are and are not “classes” (and that it’s not possible to have true classes in JavaScript) this is a great starting point. I’ve reused this code in many locations, and given it to others in my workplace. I hope it serves you well.