String Replace Forward Slash

September 2nd, 2010 Dave No comments

Pretty simple and straight forward code but it can be tricky if you dont know to use a back slash first.

document.location.pathname.replace(/\/common\//g, '').replace(/\//g, "_");

As you can see the syntax highlighter even gets confused.

Categories: JavaScript Tags: , ,

jQuery Timer Plugin

August 30th, 2010 Dave No comments

Just a simple jQuery timer plugin.

$.extend({
	x6 : {
		emptyFunction : function() {
		},

		trueFunction : function() {
			return true;
		},

		falseFunction : function() {
			return false;
		},

		/**
		 * Simple timer class
		 * @param text - text
		 * @param format - format for the timer 'm' or 's'. Defaults to milliseconds
		 */
		timer : function(text, format) {
			return {
				text : text,
				format : (format=== 's' || format==='m') ? (format==='m' ? 1 : 1000) : 1,
				startTime : new Date().getTime(),
				stop : function() {
					return (new Date().getTime() - this.startTime) / this.format;
				}
			};
		}
	}
}); 

$.fn.extend({
	/**
	 * @param evtName - event name to bind to
	 * @param callback - function callback
	 */
	timer : function(evtName,callback) {
		evtName = evtName || 'load';
		callback = callback || $.x6.emptyFunction;
		return this.each(function() {
			$(this).bind(evtName, {timer:$.x6.timer(this.tagName + ':' + (this.id||this.className||''), 'm')}, function(e) {
				if(!this.timer) {
					this.timer = e.data.timer;
				}
				callback.apply(this, []);
			});
		});
	}
});
Categories: JavaScript Tags: , ,

Array.combine

March 20th, 2010 Dave No comments

Sometimes the best frameworks miss something simple…

Array.prototype.combine = function(array) {
	if(array && array.length > 0) {
		for(var x=0;x<array.length;x++) {
			this.push(array[x]);
		}
	}
	return this;
}

This function will append the array in the parameter list to the array that is used to call the combine function. You could also daisy chain the calls!

    [1,2].combine([3,4]).combine([5,6]); //[1,2,3,4,5,6]
Categories: JavaScript Tags: , ,

Create DataSource for JUnit Tests

December 20th, 2009 Dave No comments

Testing outside of a tomcat container when using data sources you run into a problem when making jdbc connections. This is the easy way to create unit test that automatically insert your datasource. Just extend this class and when you create your test classes.

package com.xfusion6.test;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource;

/**
 * @author Dave
 *
 */
public class X6Test {
	static {
		try {
            // Create initial context
            System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
            System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
            InitialContext ic = new InitialContext();

            ic.createSubcontext("java:");
            ic.createSubcontext("java:/comp");
            ic.createSubcontext("java:/comp/env");
            ic.createSubcontext("java:/comp/env/jdbc");

            //I use this to get the data source name from web.xml file
            ic.bind("java:/comp/env/dataSourceName", "dataSourceName");

            // Construct DataSource
            MysqlConnectionPoolDataSource ds = new MysqlConnectionPoolDataSource();
            ds.setURL("jdbc:mysql://localhost:3306/user?autoReconnect=true");
            ds.setUser("user");
            ds.setPassword("password");

            ic.bind("java:/comp/env/jdbc/dataSourceName", ds);
        } catch (NamingException ex) {
            Logger.getLogger(X6Test.class.getName()).log(Level.FATAL, null, ex);
        }

	}
}
Categories: Java Tags: , , , ,

Dynamic JS Loading

August 29th, 2009 Dave No comments

Over the past year I have been looking for a good script to dynamically load dependent JavaScript files. I have found some that work and some that half-ass work. Most of them work well under certain conditions and browsers. I also needed the script to be evaluated before the rest of the script continues. So its more like a php include and all of the variables and functions are available to to dependent script.

I wrote my own script that did just that. But after 8 months in the end all of the imports and complicated “JS” inheritance it became unstable. As of now I am still not sure what actually broke it but when working in an environment where the boss says get it working, you get it working. So I abandoned the dynamic imports and went back to the old school way of including JavaScript. Now I have found something that seems to do the trick! The guys at LABjs have created a very elegant solution. The script is very useful and gives you many options. You can block scripts, load in head or body, and can also create callbacks that are fired when the script is available. Here is an example of how easy it is to use.

$LAB.toBODY()
.script('prototype-1.6.1.js')
.block()
.script('Stopwatch.js')//depends on prototype
.block()
.script('test.js'); //depends on stop watch

This example is close to just inline including in the body but you can also take this code and insert it into your scripts to load JavaScript that was not included in the html. So for example you have a script that creates some sort of widget for your page. Well so that you dont have to include the script in the html you can just import directly within that script. This way when you include the widget in a page it automatically loads all the scripts it needs to run!

Categories: JavaScript Tags: , ,

.htaccess Redirect To Directory

August 22nd, 2009 Dave No comments

Everytime I want to create redirects I always have to scour the net for the right code. Here is a simple redirect that will forward both with/without ‘www’ to a specified directory.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^mydomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^www.mydomain.com$
RewriteRule ^/?$ "http\:\/\/mydomain\.com\/myfolder" [R=301,L]

Easy JS Task Timer

August 22nd, 2009 Dave No comments

From time to time I like to time my JavaScript functions when I am trying to improve performance. I came up with a tiny script that I use during development that does just that…

Stopwatch = {
	start : function(name) {
		var startTime = new Date().getTime();
		return {
			stop: function() {
				return (new Date().getTime() - startTime);
			},
			name:name
		};
	}
};

So the object is pretty simple. So is how its used…

var count = 10000;

[function tagByName(){ document.getElementsByTagName('script'); },
function $$tag(){ $$('script'); },
function elementById(){ document.getElementById('body'); },
function $byId(){ $('body'); }].each(function(t) {
	var name = t.toString(), task;
	name = name.substring(name.indexOf(' ') + 1, name.indexOf('('));
	task = Stopwatch.start(name); //Start the timer
	for(var x=0;x<count;x+=1) {
		t.call();
	}
	console.log(task.name + ' - ' task.stop());//log it
});
Categories: JavaScript Tags: , ,