Prajwal Tuladhar’s Blog
 
programming, life and some random thoughts

Archive for the 'JavaScript' Category

Aug 06 2009

Singleton in Javascript

Published by under JavaScript

If you are familiar with design patterns then, you may also know about Singleton Pattern. It is used to restrict creation of multiple instance of a class or a class will have only one instance.

function MyClass()	{
	if (MyClass.caller.toString() != MyClass.getInstance)	{
		throw new Error("Initialization not allowed");
	}
	this.someProperty = "some value";
}
MyClass._instance = null;
MyClass.getInstance = function()	{
	if (MyClass._instance == null)
		this._instance = new MyClass();
	return this._instance;
}

var c = MyClass.getInstance();

fireunit.compare("some value", c.someProperty, "this should pass");
c.someProperty = "aa";
//try to create another instance
var d = MyClass.getInstance();
fireunit.compare("aa", d.someProperty, "new value - this should pass");
fireunit.testDone();

Here is the output of the code:

Hope this will help you :)


Comments Off

Aug 02 2009

First interaction with Mojo SDK

Palm Pre has been out for sometime and it has gained considerable attention in the industry and widely regarded as one of the challengers to iPhone and Android based phones. One of the unique features of the Palm Pre is it’s underlying software stack. The OS powering the device is called WebOS and the application framework is called Mojo. Mojo is entirely based on JavaScript and HTML so, developer don’t have to learn any new languages. Especially, if one is attached to the world of web development then, WebOS provides extra advantage.  So, I was also eager to play with it.

Mojo is a MVC framework with cetain new terms. Controllers are called assistants which are associated with with a scene or View. As a web developer, I’m also excited that I can play with HTML 5 with Mojo. There are number of widgets (UI API functions) and services (providing access to core applications, hardware, system services, and cloud services).

I downloaded and install Pre SDk in Ubuntu 9.04 and it did go well without any problem. It uses Virtual Box to run its emulator which I think is much better than that of Android (it’s VM is freaking slow).

It may be a bit biased but comparing the installation and SDK implementation, Palm Pre scores higher than Android (sorry no iPhone).

Most of the config settings are handled in JSON format which I really like (better than those ugly XML files :) ). Example of appinfo.json which is responsible for providing meta-data of an application:

{
  "id": "com.infynyxx.firstapp",
  "version": "1.0.0",
  "vendor": "Infynyxx",
  "type": "web",
  "main": "index.html",
  "title": "FirstApp",
  "icon": "icon.png"
}

I used SDK Eclipse plugin to create application.

In the above structure, first-scene-assistant.js is a controller for the view apps/views/first-scene. Here is the code which is entirely Javascript.

function FirstSceneAssistant() {
	/* this is the creator function for your scene assistant object. It will be passed all the
	   additional parameters (after the scene name) that were passed to pushScene. The reference
	   to the scene controller (this.controller) has not be established yet, so any initialization
	   that needs the scene controller should be done in the setup function below. */
}

FirstSceneAssistant.prototype.setup = function() {
	/* this function is for setup tasks that have to happen when the scene is first created */

	/* use Mojo.View.render to render view templates and add them to the scene, if needed. */

	/* setup widgets here */

	/* add event handlers to listen to events from widgets */

	this.total = 0;
	this.controller.get('count').update(this.total);

	this.buttonAttributes = {};
	this.buttonModel = {
		buttonLabel: 'TAP HERE',
		buttonClass: '',
		disabled: false
	};

	//setup button
	this.controller.setupWidget("MyButton", this.buttonAttributes, this.buttonModel);

	//bind the button to the event listener
	Mojo.Event.listen(this.controller.get('MyButton'), Mojo.Event.tap, this.handleButtonPress.bind(this));

	this.setupListSelector();
}

FirstSceneAssistant.prototype.activate = function(event) {
	/* put in event handlers here that should only be in effect when this scene is active. For
	   example, key handlers that are observing the document */
}

FirstSceneAssistant.prototype.deactivate = function(event) {
	/* remove any event handlers you added in activate and do any other cleanup that should happen before
	   this scene is popped or another scene is pushed on top */
}

FirstSceneAssistant.prototype.cleanup = function(event) {
	/* this function should do any cleanup needed before the scene is destroyed as
	   a result of being popped off the scene stack */
}

FirstSceneAssistant.prototype.handleButtonPress = function(event)	{
	this.total++;
	this.controller.get('count').update(this.total);
}

FirstSceneAssistant.prototype.setupListSelector = function()	{
	var selectorChoices = [{label: "United States", value: 1}, {label: "Nepal", value: 2}, {label: "India", value: 3}];
	var selectorAttributes = {label: 'Pick a Thing', choices: selectorChoices, modelProperty:'value' };
	this.selectorModel = {value: 2};
	this.controller.setupWidget('myListSelector', selectorAttributes, this.selectorModel);
	Mojo.Event.listen(this.controller.get("myListSelector"), Mojo.Event.propertyChange, this.handleSelectorChange.bind(this));
	return this;
}

FirstSceneAssistant.prototype.handleSelectorChange = function(event)	{
	this.controller.get('count').update(event.value);
}

Here is the corresponding view file:


<div id="main" class="palm-hasheader">
    <div class="palm-header">Header</div>
    <div id="count" class="palm-body-text" style="color: red">0</div>
    <div id="MyButton" name="MyButton1" x-mojo-element="Button"></div>
    <br/>
    <div id="myListSelector" class="palm-list-selector" x-mojo-element="ListSelector"></div>
</div>

And here is the output:

Well, this was my first shot with Mojo so, I haven’t gone so deep and still didn’t know much but I am really looking forward to go furthur with it because it makes heavy use of HTMl and JS, the language of the Web.


Comments Off

Jul 21 2009

Global Variables in Javascript

Published by under JavaScript

Normally, global variables are considered evil but in Javascript they are still used considerably.

var test = "test";
console.log(window.test == "test");

Okay, this one is usual and expected.

if (true)	{
var test = "new test";
}
console.log(window.test == "new test");

Declaring the same variable inside the expression also gives any variable global scope.

function smth()	{
var test = "no new test";
}
smth();
console.log(window.test != "no new test");

When the same variable is declared using ‘var’ keyword inside a function expression, it won’t have global impact.

function smth2()	{
test = "new new test";
}
smth2();
console.log(window.test == "new new test");

But when the same variable (test in our case) is used inside a function expression, it will continue it’s global effect.

function smth3()	{
test2 = "new variable";
}
smth3();
console.log(window.test2 == "new variable");

This case is a bit interesting and odd. Even though, test2 has not been declared earlier, it will be treated as global variable now.

Hope this help!


Comments Off

Mar 29 2009

Custom event handling with Prototype

The maturity and development of JavaScript has certainly led to more efficient handling nowadays. Remember those days when IE and Netscape had different event handling mechanisms. Well, the event handling mechanism is still different in IE and non-IE browsers, the popularity of JS libraries like Prototype, jQuery, YUI have certainly helped the web developers to fill that gap. One of the main reasons I love to use these libraries (PrototypsJS especially) is that native event handling really sucks. Forget about custom events, just in order to implement event in unobstrsuive way without those libraries you would require to consider event objects differently for IE and non-IE browsers something like this:


document.getElementsByTagName("input")[0].onkeypress = function(e)	{
	// If no event object exists, then grab the global (IE-only) one
	e = e || window.event;
	return e.keyCode != 13;		//Do nothing when Enter is pressed
}

Its just a simple tiny example but one can imagine the potential complexity that could arise in nowadays’ site with petty high use of JS.

I did know that custom event handling exist in Prototype but I believe in YAGNI and never realized its potential. But as I am working in a project with massive JS and Ajax use, finally I have seen and used how custom events can be used to invoke to control encapsulate built-in JS events and use them in quite a flexible way.

While searching on the web about thistopic I found some really nice articles.

This last article has tried to explain normal and cusom events as:

When we describe normal events to our peers as a series of interactions, we generally say something like “For this tab menu, I want to swap the colors, then change the message on ‘click’ of the tab.”. Or if that sounds too awkward. We’ll say “When the user ‘clicks’ on the tab, I want to swap the colors and change the message.”

I can see it swindling in your brain already. Sure enough, the first thing that would normally come to a scripters mind is…. “I’ll assign a ‘click’ event to the tab that fires a function which will swap the colors, then change the message”. Fair enough. That totally works and that’s the way most people do it.

A custom event in this same model can be something you, yes you, get to make up. Looking at our tab/click/swapColor/changeMessage illustration, we can easily turn this into an event called onTabChange. In return, anytime our tab menu changes state, we can notify our listeners/subscribers that this event occured; then do whatever the heck we want on the fly.

Just following the above explanation, I have come with a simple example: A test scenario where a check box determines whether to enable or disable the onchange events for elements with CSS like .input. When the checkbox is enabled, particular onchange event for particular elements are also enabled and vice-versa.

Here is the HTML Code:


<fieldset>
	<legend>
		JS Custom Events
	</legend>
	<div>
		<input type="checkbox" value="1" id="enableInputEvents" />&nbsp;Enable events for text box and combo box<br/>
	</div>
	<div id="inputs_elements">
		Text Box 1:&nbsp;<input type="text" id="textbox1" value="" class="input" /><br/>
		Text Box 2:&nbsp;<input type="text" id="textbox2" value="" /><br/>
		Select Search Engine: <select id="search-engine-selector" class="input">
			<option value="">Go to</option>
			<option value="http://www.google.com">Google</option>
			<option value="http://www.yahoo.com">Yahoo!</option>
			<option value="http://www.live.com">Live</option>
		</select>
	</div>
</fieldset>

And JavaScript code for firing custom events:


Event.observe(document, 'dom:loaded', function()	{
	$('enableInputEvents').observe('click', function(e)	{
		document.fire('CheckBox:Enabled', {checked: $('enableInputEvents').checked});
	});
});

document.observe('CheckBox:Enabled', function(e)	{
	Event.stop(e);
	if (e.memo.checked)	{
		console.log("all elements with CSS class input are ENABLED");
		$$('.input').each(function(t)	{
			t.observe('change', function()	{
				alert(t.value);
			});
		});
	}
	else	{
		console.log("all elements with CSS class input are DISABLED");
		$$('.input').invoke('stopObserving');
	}
});

Custom event handling in Prototype is a bit different than other JS libraries. And CheckBox:Enabled is a special notation type for firing custom events. Prototype API call this notation as namespace:eventname o avoid custom event names conflicting with non-standard native DOM events such as mousewheel and DOMMouseScroll.

When the Checkbox is enabled

When the Checkbox is disabled


Comments Off

Mar 28 2009

Flexible function call in JavaScript

If you have used popular JavaScript libraries like PrototypeJS, jQuery and so on (I have used only PrototypeJS and Adobe Spry), you may have noticed the flexibility of calling their API class and methods. Something like this while using PrototyeJS AJAX API:


new Ajax.Request(url, {
	onSuccess: function(response)	{
		//do something
	}
	onException: function(response, exception)	{
		//do something
	}
	onFailure: function()	{
		//do something
	}
});

I have figured out that creating a method that can handle such call is certainly not so hard and in my opinion, it does provide some level of flexibility in the code.
Here is the same code:


function clickIt(options)	{
	this.message = "";
	this.afterClick = function()	{};

	for (var key in options) {
        this[key] = options[key];
    }

	this._execute = function()	{
		alert(this.message);
		this.afterClick();
	}

	this._execute();
}

The above method accepts a single object as an argument with two properties: message and afterClick and this._execute() is a kinda private method (JavaScript does not have an explicit access modifier). Now to call the above function:


Event.observe(window, 'load', function()	{
	$('iclick').observe('click', function(e)	{
		Event.stop(e);
		new clickIt({
			message: "This is some message",
			afterClick: function()	{
				if (confirm("Are you sure"))	{
					window.location.replace(this.href);
				}
			}
		});
	});
});

Since {} is regarded as object in JavaScript so one can use it to make a function/class more flexible and extensible. But since, users calling this class will have no knowledge what arguments are acceptable so, documentation plays crucial role (If you are creating an API then, the success and usability of that API heavily depends on the quality of documentation that acts as valid contract between interface and implementation code).


Comments Off

« Prev - Next »

RSS Feed
Subscribe by email
Follow me @ Twitter