Archive for the ‘JavaScript’ Category

HTML5: Display local images without going to server

Wednesday, January 25th, 2012

Note: assuming jquery

// get the input element
var $fileElement = $("input[type='file']");
var $image = $("img:first");

// on change
$fileElement.on("change",function(){
   if (this.files && this.files.length > 0){
       var file = this.files[0];
       var reader = new FileReader();
       reader.onload = function(e) {
	   $img.attr("src", e.target.result);
       }
       reader.readAsDataURL(file);
   }
});

JavaScript: implementing a javascript component (bestpractice)

Sunday, July 31st, 2011

Here is a best practice to implement a javascript component. (code skeleton)

// do this one per file
var myModule = myModule || {}


// Do an "scoping function" once per Component
(function($){

  // some privates members here

  // --------- myModule.MyComponent Constructor --------- //
  myModule.MyComponent = function MyComponent(arg1,argN){

    // little trick allowing to instanciate any of the two following ways:`
    //   1) var comp = new myModule.MyComponent(..)
    //   2) var comp = myModule.MyComponent(..)
    if (!(this instanceof MyComponent)) {
    	return new MyComponent(arg1,argN);
    }
  }
  // --------- /myModule.MyComponent Constructor --------- //

  // --------- Public Methods --------- //
  myModule.MyComponent.prototype.publicMethodA = function(){
     // some stuff
  }
  // --------- /Public Methods --------- //


  //private methods here
  function privateMethodB(){

  }
})(jQuery);

javascript: OAuth with iOS, PhoneGap, and Chrome Extension

Friday, June 10th, 2011

Javascript: sort an array of json object by a property

Monday, May 30th, 2011
// a is the array to be sorted
function(a,propName){
		return a.sort(sortByFunc);
		function sortByFunc(a, b) {
			if (typeof a === "undefined") return -1;
			if (typeof b === "undefined") return 1;

		    var x = a[propName];
		    var y = b[propName];
		    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
		}
}

JavaScript: arguments to Array

Thursday, April 28th, 2011

The arguments variable is not a true array, so, to convert it to an array to pass them to another method, here it is.

function hello() {
    var args = Array.prototype.slice.call(arguments);
    myOtherFunction.apply(this,args);

}

JavaScript: Aspect (AOP) in JavaScript

Monday, March 28th, 2011

Great javascript lib for AOP: jQuery-AOP jQuery-AOP-Reference (just use the jQuery namespace)

before

jQuery.aop.before( {target: String, method: 'replace'},
  function(regex, newString) {
    alert("About to replace string '" + this +
           "' with '" + newString + "' using regEx '" + regex + "'");
  }
);

arround

jQuery.aop.around( {target: String, method: 'indexOf'},
  function(invocation) {
    alert('Searching: ' + invocation.arguments[0] + ' on: ' + this);
    return invocation.proceed();
  }
);

JavaScript: Sort an array of objects

Sunday, March 13th, 2011

The data:

var myData = new Array();
myData[0] = {FirstName:"John", LastName:"Doe", Age:40};
myData[1] = {FirstName:"Fred", LastName:"Smith", Age:41};

The sort function:

function sortByFirstName(a, b) {
    var x = a.FirstName.toLowerCase();
    var y = b.FirstName.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

Sorting:

myData.sort(sortByFirstName);

Source: breakingpar.com: JavaScript Sorting

snowUI: Template to create a snowUI DAO

Monday, December 27th, 2010
var MockUserDao = (function(){

    var somePrivateStuff = null;

	// Object function
	function MockUserDao(){};

	// ------ DAO Interface ------ //
	MockUserDao.prototype.getUser = function(objType,id){
	  somePrivateFunction();
	  ....
	}

	....
	// ------ /DAO Interface ------ //

	// ------ Privates ------- //
	function somePrivateFunction(){
	....
	}
	// ------ Privates ------- //

	return MockUserDao;
})());

snow.dm.registerDao("user",new MockUserDao());

Javascript: Split a string into characteres

Wednesday, December 1st, 2010
"test 2".match(/./g)

Will return:

["t", "e", "s", "t", " ","2"]

Javascript: JSON Stringify, Parse, and HTML5 local storage

Monday, October 4th, 2010

Stringify

jsonString = JSON.stringify(value [, replacer [, space]])
source

var jsonString = JSON.stringify({name:"Mike",age:22});
//jsonString = '{"name":"Mike","age":22}'

Parse

var jsObject = JSON.parse('{"name":"Mike","age":22}');

Storage

  • length: Retrieves the number of key/value pairs in the list
  • key(index): Returns the key at the specified index
  • getItem(key): Returns the value associated with the given key
  • setItem(key, value): Sets a key/value pair
  • removeItem(key): Removes the item with the specified key
  • clear(): Removes all key/value pairs

LocalStorage Example:

var mikeInfo = JSON.stringify({name:"Mike",age:12});
localStorage.setItem("mikeInfo",mikeInfo);
Source: Web Storage

Other Links

  • json2 (json stringify/parser util)