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

Archive for the 'JavaScript' Category

Dec 03 2009

Node.js: Changing the way we do I/O

Published by Prajwal Tuladhar under JavaScript

Node.js might be the most exciting single piece of software in the current JavaScript universe. Ryan received standing ovations for his talk and he really deserved it!

http://jsconf.eu/2009/video_nodejs_by_ryan_dahl.html

I tried Node.js last week and I was quite impress. Truly, Node.js has the potential to change the way we do I/O. Basically it’s an evented programming concept build on underlying stack of Python and C++ while using Google’s V8 (JavaScript Engine) as an interfacing language capable of performing network programming (using polling) in different way. Here are some of the key design goals of this technology:

  • No function should direct perform I/O (Use Callback to do so)
  • Stream everything, never force the buffering of data (Somewhat like comet)
  • Have built-in support for the most important protocols: HTTP, DNS, TCP
  • Support many HTTP features: Chunked requests, Keep-alive, Hang Requests for comet applications
  • Bridge API somewhere between flexibility of client side JavaScript and old Unix tools
  • Platform independent
Example:
Simple Twitter Client I wrote last week:

var http = require("http"),
	sys = require("sys");
var connection = http.createClient(80, "twitter.com");
var since_id = '';
var interval = 0;
function getTweets()	{
	var url = "/statuses/friends_timeline.json";
	if (since_id != '')	{
		url += "?since_id=" + since_id;
	}
	var request = connection.get(url, {
		"content-type": "application/json",
		"User-Agent": "NodeJS HTTP Client by Infynyxx",
		"host": "twitter.com",
		"Authorization": "Basic " + Base64.encode("infynyxx:*****")
	});
	request.finish(function(response)	{
		var responseBody = "";
		response.setBodyEncoding("utf8");
		response.addListener("body", function(chunk)	{
			responseBody += chunk;
		});
		response.addListener("complete", function()	{
			var tweets = JSON.parse(responseBody);
			if (tweets.error)	{
				sys.puts("Error: " + tweets.error);
			}
			else	{
				var length = tweets.length;
				if (length > 0)	{
					sys.puts("Getting new tweets...\n");
					sys.puts("Number of new tweets: " + length + "\n");
					var str = "";
					tweets.reverse();
					tweets.forEach(function(element, index) {
						str += element.text + "\n";
						str += element.user.name + "\n";;
						str += element.created_at + "\n";;
						str += "*************************\n";
					});
					sys.puts(str);
				}
			}
		});
	});
	setTimeout(getTweets, interval);
	interval = 300000;  //5 minutes
}

getTweets();

It also uses Base64 library. Full Code @ Gitgub


Comments

Sep 19 2009

WebGL / Canvas 3D in Webkit

Published by Prajwal Tuladhar under JavaScript

The demo for WebGL API looks awesome.

Source


Comments

Aug 06 2009

Singleton in Javascript

Published by Prajwal Tuladhar 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

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

Jul 21 2009

Global Variables in Javascript

Published by Prajwal Tuladhar 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

Next »

RSS Feed
Subscribe by email
Follow me @ Twitter