<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Undisciplined Bytes &#187; javascript</title>
	<atom:link href="http://www.undisciplinedbytes.com/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.undisciplinedbytes.com</link>
	<description>Web Application Development Tips, Tricks and Techniques</description>
	<lastBuildDate>Tue, 31 Jan 2012 09:07:24 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>JavaScript best practices II</title>
		<link>http://www.undisciplinedbytes.com/2011/02/javascript-best-practices-ii/</link>
		<comments>http://www.undisciplinedbytes.com/2011/02/javascript-best-practices-ii/#comments</comments>
		<pubDate>Tue, 22 Feb 2011 10:35:08 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[browser]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=552</guid>
		<description><![CDATA[We’ve seen some basic recommendations we should all follow when writing  JavaScript. Now let’s go through some more:


Comment as much as needed, but no more: comment what you consider needed,  but don’t tell others your life story. Too many comments may make some other  developer get distracted from the actual code.
Javascript is [...]]]></description>
			<content:encoded><![CDATA[<p>We’ve seen some basic recommendations we should all follow when writing  JavaScript. Now let’s go through some more:</p>
<p><span id="more-552"></span></p>
<ul>
<li>Comment as much as needed, but no more: comment what you consider needed,  but don’t tell others your life story. Too many comments may make some other  developer get distracted from the actual code.</li>
<li>Javascript is used to define the behaviour, not the look &amp; feel: even  though there’s the possibility to set the appearance of your application through  JavaScript, you should leave that for CSS. Always follow the “separation of  concerns” mantra. A change in the icons or the color of borders shouldn’t  require dealing with JavaScript code.</li>
<li>Modularize: keep your code modularized and specialized. Make sure to write  smaller, generic helper functions that fulfill one specific task, rather than  catch-all methods.</li>
<li>Allow for configuration and translation: everything that is likely to change  in your code should not be scattered throughout the code, for example, labels,  CSS classes and IDs. By putting these into a configuration object and making it  public, we make maintenance very easy and allow for customization.</li>
<li>Access the DOM as little as possible: accessing the DOM in browsers is an  expensive thing to do. The DOM is a very complex API and rendering in browsers  can take up a lot of time. To make sure that your code is fast and doesn’t slow  down the browser to a halt try to keep DOM access to a bare minimum.</li>
<li>Build on the shoulders of giants: JavaScript libraries are specifically  built to make browsers behave as you would expect by plugging browser holes.  Therefore, if you want to write code that works without keeping the maintenance  overhead of supporting current browsers and those to come, start with a good  library.</li>
<li>Development code is not live code: live code is done for machines,  development code is done for humans. Make your code as readable and  understandable as possible. Then, before deploying your web application,  collate, minify and optimize your code in a build process.</li>
</ul>
<p>If you follow all these recommendations, you can be sure you’ll have produced  a high quality code that will be easy to maintain.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2011/02/javascript-best-practices-ii/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript best practices I</title>
		<link>http://www.undisciplinedbytes.com/2011/01/javascript-best-practices-i/</link>
		<comments>http://www.undisciplinedbytes.com/2011/01/javascript-best-practices-i/#comments</comments>
		<pubDate>Mon, 31 Jan 2011 12:43:41 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[browser]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/2011/01/javascript-best-practices-i/</guid>
		<description><![CDATA[Now that we’ve seen the basic JavaScript concepts, we’ll go through some recommendations to make a good code. These are some practices that should be followed if you want to make a readable and maintainable code. It is based on my knowledge and experience of JavaScript over several years of practical experience:


Always use ‘var’: although [...]]]></description>
			<content:encoded><![CDATA[<p>Now that we’ve seen the basic JavaScript concepts, we’ll go through some recommendations to make a good code. These are some practices that should be followed if you want to make a readable and maintainable code. It is based on my knowledge and experience of JavaScript over several years of practical experience:</p>
<p><span id="more-548"></span></p>
<ul>
<li>Always use ‘var’: although it is not compulsory, the use of the ‘var’ keyword is always recommended. By using it, your code will execute faster, and you will avoid some potential problems.</li>
<li>Feature-detect rather than browser-detect: before using any advanced feature that an older browser may not support, check to see if the function or property exists first, instead of writing code to detect browser versions.</li>
<li>Avoid ‘eval’: the eval() function in JavaScript allows a programmer to run arbitrary code at run-time, by interpreting a string as if it was code. If it exists in your page, there is almost always a more correct way to accomplish what you are doing. “Eval is evil.&#8221; Don&#8217;t use it unless you are an experienced developer and know that your case is an exception.</li>
<li>Use unobstrusive JavaScript: now, this is an important one: HTML and JavaScript code should not be mixed together. You should always follow the “separation of concerns” mantra: HTML defines the structure and content of a web page, and JavaScript defines the behavior. Therefore, do not use inline event handlers. Attach your event-handling code by JavaScript. This way, you’ll improve readability and maintainability.</li>
<li>Avoid cluttering the global namespace: global variables and functions are rarely required. Using globals may cause naming conflicts between JavaScript source files and cause code to break. You should always use object oriented programming and write all your code in classes when writing JavaScript code.</li>
<li>Use JSON: when storing data structures as plain text or sending/retrieving data structures via Ajax, use JSON instead of XML when possible. JSON (JavaScript Object Notation) is a more compact and efficient data format, and is language-neutral.</li>
<li>Make you code understandable: choose easy to understand and short names for variables and functions. Think of your code as a story – a story that should be easy to read and understand, the names you choose shouldn’t make it more complicated.</li>
</ul>
<p>In my next post I’ll discuss some more recommendations. Stay tuned!</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2011/02/javascript-best-practices-ii/' rel='bookmark' title='Permanent Link: JavaScript best practices II'>JavaScript best practices II</a></li>
<li><a href='http://www.undisciplinedbytes.com/2011/01/object-oriented-javascript-iii-some-tips/' rel='bookmark' title='Permanent Link: Object Oriented JavaScript III: some tips'>Object Oriented JavaScript III: some tips</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-i-the-basics/' rel='bookmark' title='Permanent Link: Object Oriented JavaScript I: the basics'>Object Oriented JavaScript I: the basics</a></li>
<li><a href='http://www.undisciplinedbytes.com/2009/10/javascript-frameworks-overview/' rel='bookmark' title='Permanent Link: Javascript frameworks overview'>Javascript frameworks overview</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-ii-the-pattern/' rel='bookmark' title='Permanent Link: Object Oriented JavaScript II: the pattern'>Object Oriented JavaScript II: the pattern</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2011/01/javascript-best-practices-i/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Object Oriented JavaScript III: some tips</title>
		<link>http://www.undisciplinedbytes.com/2011/01/object-oriented-javascript-iii-some-tips/</link>
		<comments>http://www.undisciplinedbytes.com/2011/01/object-oriented-javascript-iii-some-tips/#comments</comments>
		<pubDate>Thu, 13 Jan 2011 12:47:38 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software engineering]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=531</guid>
		<description><![CDATA[We’ve already gone through the basic JavaScript concepts we need to write object oriented code, and we’ve already seen the basic pattern. But here’s a couple of tips that has proven useful many times when writing long and complex JavaScript code.
The curious case of the mutating scope
Ok, now imagine we have some fancy widget in [...]]]></description>
			<content:encoded><![CDATA[<p>We’ve already gone through the basic JavaScript concepts we need to write object oriented code, and we’ve already seen the basic pattern. But here’s a couple of tips that has proven useful many times when writing long and complex JavaScript code.</p>
<h4>The curious case of the mutating scope</h4>
<p>Ok, now imagine we have some fancy widget in our class and we want to interact with it. There are many widgets which redefine the <code>this</code> keyword to its instance instead of ours. For this case, we might want to be able to access our instance instead of the widget instance. We’ll need to redefine the scope in which the function is being executed. To do so, we can use the following function:</p>
<pre class="brush:javascript">// Creates a new function and returns a reference. This new function has its scope set to 'newScope'
this.setScope = function (originalFn, newScope) {
   return function () { return originalFn.apply(newScope, arguments); };
};</pre>
<p>We could just use the apply method on our original function, but I prefer this way since its more comfortable to work with parameters like this.</p>
<p>Be careful when using this, since this is a double-edged sword. By accessing our class scope we have all our data available. But we won’t have the widget’s scope available anymore. So make sure you don’t need to access the widget’s scope before changing the scope of the event handler.</p>
<p><span id="more-531"></span></p>
<h4>Accessing your instance from the global scope</h4>
<p>When you do something like</p>
<p><code>var Peter = new Person();</code></p>
<p>you&#8217;re creating a new instance of the class <code>Person</code>. And the variable <code>Peter</code> is just a pointer to the instance, not the instance itself. <code>Peter</code> is the way we have to access that instance from global scope: it’s just a pointer. But we have no way to know the name the pointer to the instance was given from within the instance itself. This means, we have no way to know that <code>Peter</code> is the way we have to access the instance from global scope.</p>
<p>So, if we’re ever in the need of calling a method from a global scope, we’ll need to keep an array of instances ourselves. We could be doing something like:</p>
<pre class="brush:javascript">var Person2 = function (name, surname, age) {
	var _name, _surname, _age;

	this.showData = function () {
		var str = new String();
		str = "Name: " + _name + " - ";
		str += "Surname: " + _surname + " - ";
		str += "Age: " + _age;
		alert(str);
	};	

	// ---- Constructor -----------------------------------------------
	_name = (typeof name === "undefined" ? "John" : name);
	_surname = (typeof surname === "undefined" ? "Smith" : surname);
	_age = (typeof age === "undefined" ? 20 : age);

	// Store pointers to all instances of this class, so we can access their
	// context from global code
	var _instanceIndex = Person2._instances.length;
	Person2._instances[_instanceIndex] = this;
};
Person2._instances = new Array();</pre>
<p>So now we have an array containing all the different instances of the object:</p>
<pre class="brush:javascript">var Peter = new Person2();  // Equivalent to Person2._instances[0]
var John = new Person2('John', 'Smith');  // Equivalent to Person2._instances[1]</pre>
<p>This is useful if you’re declaring some event handlers in the HTML code. Something like:</p>
<pre>&lt;div id="myDiv" onclick="Person2._instances[1].showData();"&gt;Hello world!&lt;/div&gt;</pre>
<p><strong>CAUTION!! This is not something I would recommend. This is not a good practice in JavaScript. Behaviour should be separated from the content, and with this you’re just mixing both together.</strong></p>
<p>I’m just showing this as a possibility, in case you’re in the need of something similar. But be aware that by using <code>onclick</code> event handlers like this, you’re making your code less readable and less maintainable. <strong>Be careful!</strong></p>
<p>Well, now you have to start practicing all these concepts you’ve just read. Start doing some JavaScript programming. The more you do it, the better programmer you’ll become.</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-ii-the-pattern/' rel='bookmark' title='Permanent Link: Object Oriented JavaScript II: the pattern'>Object Oriented JavaScript II: the pattern</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-i-the-basics/' rel='bookmark' title='Permanent Link: Object Oriented JavaScript I: the basics'>Object Oriented JavaScript I: the basics</a></li>
<li><a href='http://www.undisciplinedbytes.com/2011/01/javascript-best-practices-i/' rel='bookmark' title='Permanent Link: JavaScript best practices I'>JavaScript best practices I</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2011/01/object-oriented-javascript-iii-some-tips/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Object Oriented JavaScript II: the pattern</title>
		<link>http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-ii-the-pattern/</link>
		<comments>http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-ii-the-pattern/#comments</comments>
		<pubDate>Tue, 21 Dec 2010 15:30:34 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software engineering]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=481</guid>
		<description><![CDATA[Ok, now that we’ve covered the most basic concepts of JavaScript, we can now proceed to take a look at the pattern itself.
The first feature we need to implement is private and public members. Using closures, this is easy to achieve:

var Person = function () {
	// Private elements
	var _name, _surname, _age;

	// Public elements
	this.getName = function [...]]]></description>
			<content:encoded><![CDATA[<p>Ok, now that we’ve covered the most basic concepts of JavaScript, we can now proceed to take a look at the pattern itself.</p>
<p>The first feature we need to implement is private and public members. Using closures, this is easy to achieve:</p>
<p><span id="more-481"></span></p>
<pre class="brush:javascript">var Person = function () {
	// Private elements
	var _name, _surname, _age;

	// Public elements
	this.getName = function () {
		return _name;
	};
	this.setName = function (newName) {
		_name = newName;
	};
	this.getSurname = function () {
		return _surname;
	};
	this.setSurname = function (newSurname) {
		_surname = newSurname;
	};
	this.getAge = function () {
		return _age;
	};
	this.setAge = function (newAge) {
		_age = newAge;
	};
};</pre>
<p>By declaring functions inside the outer function <code>Person</code>, we’re creating a closure which makes the elements <code>_name</code>, <code>_surname</code> and <code>_age</code> inaccessible by members which are not inside the <code>Person</code> function. On the contrary, all elements declared with the <code>this</code> keyword will be accessible from outside of the <code>Person</code> function.</p>
<p>If we want to set some code to be executed when this class is instantiated, we can do so anywhere inside the Person function:</p>
<pre class="brush:javascript">var Person = function (name, surname, age) {
	// Private elements
	var _name, _surname, _age;

	// Public elements
	this.getName = function () {
		return _name;
	};
	this.setName = function (newName) {
		_name = newName;
	};
	this.getSurname = function () {
		return _surname;
	};
	this.setSurname = function (newSurname) {
		_surname = newSurname;
	};
	this.getAge = function () {
		return _age;
	};
	this.setAge = function (newAge) {
		_age = newAge;
	};

	// Default constructor
	this.setName(typeof name === "undefined" ? "John" : name);
	this.setSurname(typeof surname === "undefined" ? "Smith" : surname);
	this.setAge(typeof age === "undefined" ? 20 : age);
};</pre>
<p>This way, we’re creating constructors.  If the <code>name</code>, <code>surname</code> and <code>age</code> variables are given a value when this class is instantiated, that value will be assigned to the private properties; if not, then default values will be used. So we can now check how what we’ve written behaves so far. I’ll use the <a title="firebug" href="http://getfirebug.com/" target="_blank">Firebug </a>console to check what our JavaScript does:</p>
<pre class="brush:javascript">&gt;&gt;&gt; var John = new Person()
&gt;&gt;&gt; John.getName()
"John"
&gt;&gt;&gt; John.getSurname()
"Smith"
&gt;&gt;&gt; John.getAge()
20
&gt;&gt;&gt; var Peter = new Person("Peter", "Jackson")
&gt;&gt;&gt; Peter.getName()
"Peter"
&gt;&gt;&gt; Peter.getSurname()
"Jackson"
&gt;&gt;&gt; Peter.getAge()
20</pre>
<p>Notice how private properties get the the default values if we instantiate the class with no values for the constructor.</p>
<p>So we now have private and public elements, the most basic features of object oriented techniques. But there’s actually different kinds of public properties. Depending on how you declare them, some public elements will actually behave slightly different:</p>
<pre class="brush:javascript">var Person = function (name, surname, age) {
	// ---- Private members ------------------------
	var _name, _surname, _age;

	// ---- Public, privileged members ------------------------
	// Privileged members are exposed through the API and have access to
	// private members

	this.getName = function () {
		return _name;
	};
	this.setName = function (newName) {
		_name = newName;
	};
	this.getSurname = function () {
		return _surname;
	};
	this.setSurname = function (newSurname) {
		_surname = newSurname;
	};
	this.getAge = function () {
		return _age;
	};
	this.setAge = function (newAge) {
		_age = newAge;
	};

	// ---- Default constructor ------------------------
	this.setName(typeof name === "undefined" ? "John" : name);
	this.setSurname(typeof surname === "undefined" ? "Smith" : surname);
	this.setAge(typeof age === "undefined" ? 20 : age);
};

// ---- Public, non-privileged members ------------------------
// All elements included in the prototype are exposed through the API and
// do not have access to private members.
// All instances of this class will have these members available.
Person.prototype.getPersonData = function () {
	var str = new String();
	str = "Name: " + this.getName() + " - ";
	str += "Surname: " + this.getSurname() + " - ";
	str += "Age: " + this.getAge();
	return str;
};

// ---- Public, static member for current instance ------------------------
// Members defined like this are related to the object itself, not to instances.
// These members have no means of accessing instance or private data.  They can't
// access instance data because they don't have the "this" operator set to any
// particular instance.
// These members relate to the instance in which they are defined. Since we're defining
// them for the class definition, instances of this class will not have these members
// available.
Person.AreEqual = function (p1, p2) {
	return p1.getName() === p2.getName() &amp;&amp;
			p1.getSurname() === p2.getSurname() &amp;&amp;
			p1.getAge() === p2.getAge();
};</pre>
<p>Notice how depending on how you declare your public members, they will have different access level to the information within your instance:</p>
<ul>
<li>Members declared inside the closure with the <code>this</code> keyword are privileged: they have access to private members.</li>
<li>Members declared with the <code>prototype</code> keyword are non-privileged: they do not have access to private members. These members will be available in all instances of this class.</li>
<li>Members declared like “class name” + “.” + “member name” are public static members for the current instance. They don’t have the “this” operator available, and other instances of this class will not have these members available.</li>
</ul>
<p>So, here’s how our class behaves:</p>
<pre class="brush:javascript">&gt;&gt;&gt; var John = new Person()
&gt;&gt;&gt; John.getPersonData()
"Name: John - Surname: Smith - Age: 20"
&gt;&gt;&gt; Person.AreEqual(new Person(), John)
true
&gt;&gt;&gt; var Peter = new Person("Peter")
&gt;&gt;&gt; Person.AreEqual(John, Peter)
false
&gt;&gt;&gt; John.AreEqual(John, Peter)
TypeError: John.AreEqual is not a function { message="John.AreEqual is not a function", more...}</pre>
<p>Notice how the <code>AreEqual</code> method is only available for the object <code>Person</code>, not for its instances.</p>
<p>Ok, now we’ve covered public and private elements, constructors and the different access levels public members may have. We&#8217;ve gone through all we need to write object oriented code. But keep on reading to see some tips about OO code in JavaScript.</p>
<p>Stay tuned for my next post!</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2011/01/object-oriented-javascript-iii-some-tips/' rel='bookmark' title='Permanent Link: Object Oriented JavaScript III: some tips'>Object Oriented JavaScript III: some tips</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-i-the-basics/' rel='bookmark' title='Permanent Link: Object Oriented JavaScript I: the basics'>Object Oriented JavaScript I: the basics</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-ii-the-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Object Oriented JavaScript I: the basics</title>
		<link>http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-i-the-basics/</link>
		<comments>http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-i-the-basics/#comments</comments>
		<pubDate>Thu, 02 Dec 2010 10:06:14 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software engineering]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=474</guid>
		<description><![CDATA[Today’s web applications are inconceivable without the use of JavaScript. It has become a fundamental part in modern web systems. A lot of time and effort must be put into client-side programming to make our application have that modern look &#38; feel that JavaScript provides and we all like to see.
Until AJAX techniques emerged, JavaScript [...]]]></description>
			<content:encoded><![CDATA[<p>Today’s web applications are inconceivable without the use of JavaScript. It has become a fundamental part in modern web systems. A lot of time and effort must be put into client-side programming to make our application have that modern look &amp; feel that JavaScript provides and we all like to see.</p>
<p>Until AJAX techniques emerged, JavaScript was not seen as an application development platform. It was treated merely as a scripting language to implement minimal dynamic web page behavior. Up till not too long ago, all the JavaScript I needed to write was just a few lines of code to make some validations, a few animations and some AJAX calls… but this has definitely changed today. The number of JavaScript lines I am writing nowadays for the web apps I’m developing are counted in the thousands. Heck, the last module I developed at work contained more than 12000 lines of JavaScript code! This means that I can no longer just write code without order. I need to have some logic behind the process of writing code. And this is when object oriented techniques come into play.</p>
<p><span id="more-474"></span></p>
<p>Much has been written about JavaScript and how to use its object oriented features. The thing is, although JavaScript has some object oriented (OO) features, how to use them is not a trivial matter. JavaScript (JS) is quite different from other OO languages like C# or Java, so if you’re coming from these types of languages, after some while you’ll realize that JS behaves differently in a few ways. It’s not that it’s better or worse, it’s just different. And if you ever want to get to master JS, you’ll need to be aware of them.</p>
<p>There’s a bunch of different approaches on how to use OO features and techniques. The most widely spread methodology for writing classes is the <a title="module pattern" href="http://yuiblog.com/blog/2007/06/12/module-pattern" target="_blank">module pattern</a>, made popular by the <a title="YUI JavaScript library" href="http://developer.yahoo.com/yui/" target="_blank">YUI JavaScript library</a>.</p>
<p>I’ve spent some time digging through the internet trying to find what the best pattern for OO JavaScript is. Unfortunately, there doesn’t seem to be any kind of standard, and people just implement whatever better suits their needs. So, looking around, I came up with my own pattern for writing classes and object oriented JavaScript. It is somehow derived from stuff that I’ve seen throughout the web, and with some additional features I consider useful.</p>
<p>But before explaining this pattern, you first need to understand some basics about JavaScript:</p>
<p><strong>JavaScript has loose typing.</strong> At any given time, the type of a variable is the type of whatever is assigned to it. I could perfectly do something like:</p>
<pre class="brush:javascript">var myVariable = 34;
myVariable = "Hi there!";</pre>
<p>And no error would be thrown.</p>
<p><strong>JavaScript has anonymous functions</strong>. To show this concept I&#8217;ll use the function <code>setTimeout</code>, which is used for executing some code after some specified amount of time:</p>
<pre class="brush:javascript">function sayHi() {
   alert("Hi!");
};
setTimeout(sayHi, 1000);</pre>
<p>This shows a message with the text “Hi!” after 1000 ms. The same thing can be achieved by an anonymous function:</p>
<pre class="brush:javascript">setTimeout(function () { alert("Hi!"); }, 1000);</pre>
<p><strong>JavaScript has function pointers</strong>. The previous function can be expressed as:</p>
<pre class="brush:javascript">var sayHi = function () {
   alert("Hi!");
};</pre>
<p>And it would still be called in the same way, <code>sayHi().</code></p>
<p><strong>JavaScript has closures</strong>. Now, this is a little bit tricky. Closures are something which is not fully understood by all programmers. But they really aren’t all that complicated. Let’s take a look at them:</p>
<p>A &#8220;closure&#8221; is an expression (usually a function) that has variables together inside an environment that binds those variables. In other languages, when a function is called, a new stack frame is created and then destroyed when the function completes. So, if a function is called 3 times, 3 different stack frames are created with 3 different set of local variables. JavaScript behaves differently. In JS, it is as if the stack frame for the closure was not deallocated from memory when the function returns. It&#8217;s as if it was given a static piece of memory and always stayed there. So if you call the closure 3 times, the same set of local variables are accessed, having the same value. That means, having the last value they had the last time that closure was called.</p>
<p>An example to clarify things a little. Take a look at this piece of code:</p>
<pre class="brush:javascript">function initGlobalVariables {
   var someNumber = 123;
   var someString = "Hello World!";
   var someFunction = function () { alert(someString); };
};</pre>
<p>By writing a function inside some other function, we’re creating a closure. The scope of the inner function is the outer function: this means that the function assigned to <code>someFunction</code> can access the variables <code>someNumber</code> and <code>someString</code>. And every time we call the function assigned to <code>someFunction</code>, the variables will not be created and destroyed: they will remain there with the last value they had.</p>
<p>Just remember these key facts for closures:</p>
<ul>
<li>A closure is the local variables for a function &#8211; kept alive after the function has returned.</li>
<li>Whenever you use a function inside another function, a closure is used.</li>
<li>Whenever you call the outer function, a new closure is created.</li>
<li>Whenever you call an inner function of the closure, no new closure is created: you access the existing closure with the last values they had the last time you exited an inner function of the closure.</li>
</ul>
<p><strong>The <code>this</code> keyword refers to the closure within it is located.</strong> The value of the <code>this</code> keyword refers to the scope of the function. That is, the closure within it exists.</p>
<p>Ok, with this we’ve covered the very basics of JavaScript we need to understand object oriented techniques. In my next post I’ll start covering the pattern, so stay tuned!</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-ii-the-pattern/' rel='bookmark' title='Permanent Link: Object Oriented JavaScript II: the pattern'>Object Oriented JavaScript II: the pattern</a></li>
<li><a href='http://www.undisciplinedbytes.com/2011/01/object-oriented-javascript-iii-some-tips/' rel='bookmark' title='Permanent Link: Object Oriented JavaScript III: some tips'>Object Oriented JavaScript III: some tips</a></li>
<li><a href='http://www.undisciplinedbytes.com/2011/01/javascript-best-practices-i/' rel='bookmark' title='Permanent Link: JavaScript best practices I'>JavaScript best practices I</a></li>
<li><a href='http://www.undisciplinedbytes.com/2011/12/persistence-layer-object-relational-mapping-tools/' rel='bookmark' title='Permanent Link: Persistance layer: object-relational mapping tools'>Persistance layer: object-relational mapping tools</a></li>
<li><a href='http://www.undisciplinedbytes.com/2011/02/javascript-best-practices-ii/' rel='bookmark' title='Permanent Link: JavaScript best practices II'>JavaScript best practices II</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/12/object-oriented-javascript-i-the-basics/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>HTML 5 C# Web Sockets server and ASP.NET client implementation</title>
		<link>http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/</link>
		<comments>http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/#comments</comments>
		<pubDate>Tue, 22 Jun 2010 15:02:14 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=396</guid>
		<description><![CDATA[In the previous post we saw that Web Sockets are the best invention since sliced bread: they bring to the web the bidirectional full-duplex communication traditional desktop applications have been enjoying for quite some time now. It solves many current problems, and enables much more powerful applications than current standards.
I’ve developed a very basic Web [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a title="HTML 5 Web Sockets" href="http://www.undisciplinedbytes.com/2010/05/html-5-web-sockets/" target="_blank">previous post</a> we saw that Web Sockets are the best invention since sliced bread: they bring to the web the bidirectional full-duplex communication traditional desktop applications have been enjoying for quite some time now. It solves many current problems, and enables much more powerful applications than current standards.</p>
<p>I’ve developed a very basic Web Socket server implementation in C# just as a proof of concept. It handles the most basic operations you would expect from a server: start a new connection, disconnect, and send and receive data. Besides, I’ve developed the client part as well using regular ASP.NET. Actually it’s just plain HTML and JavaScript being served from an ASP.NET server – this example doesn’t use any fancy <em>runat=server </em>controls or anything of the like. The functionality is achieved with very simple and easy to understand JavaScript.</p>
<p><span id="more-396"></span></p>
<p>So what does this example do? It provides two projects: a Web Socket server and a Web Socket client. The server is a windows console application that once executed just sits there waiting for a connection request. When a client connects, the server sends its date and time to the client every 10 seconds. The client is a web page with some controls to connect/disconnect and to send data to the server, as well as a log window to see what’s going on. Take a look at the example at the bottom of the page.</p>
<p>Here’s a description of the public members of the Web Socket Server:</p>
<pre class="brush:c#">// Possible status of the server
enum ServerStatusLevel { Off, WaitingConnection, ConnectionEstablished };
// Constructor of the server with default values
WebSocketServer();
// Constructor of the server with the specified values
WebSocketServer (int serverPort, string serverLocation, string connectionOrigin);
// Close the server and release all resources
void Dispose();
// Start the server and make it listen for connection requests
void StartServer();
// Send data to the connected client
void Send (string message);
// Whether events should be logged or not
bool LogEvents;
// Origin of the connection
string ConnectionOrigin;
// Location of the server
string ServerLocation;
// Port of the server
int ServerPort;
// Current status of the server
ServerStatusLevel Status;
// Fired when data is received from the client
event DataReceivedEventHandler DataReceived;
// Fired when client is disconnected
event DisconnectedEventHandler Disconnected;
// Fired when a new connection is established
event NewConnectionEventHandler NewConnection;</pre>
<p>Note how I provide two constructors for the Web Socket Server class: one with default parameters (if you want to keep it as simple as possible), and another one to specify the values you want. Anyways, you can still change them after creating the new instance, as the properties are public. You can also specify whether you want the server to log out the events to the console with the <code>LogEvents</code> property.</p>
<p>In order to get the data being sent from the client, you must attach your own function to the <code>DataReceived</code> event, which will then receive the message as a parameter.</p>
<p>So here’s how you would use this Web Socket Server:</p>
<pre class="brush:c#">public void Test()
{
    WebSocketServer WSServer = new WebSocketServer();  // Default values
    WSServer.NewConnection += new NewConnectionEventHandler(WSServer_NewConnection);
    WSServer.Disconnected += new DisconnectedEventHandler(WSServer_Disconnected);
    WSServer.DataReceived += new DataReceivedEventHandler(WSServer_DataReceived);
    WSServer.StartServer();
}

void WSServer_DataReceived(string message, EventArgs e)
{
    Console.WriteLine("Data received from the client: " + message);
}

void WSServer_Disconnected(EventArgs e)
{
    Console.WriteLine("Server disconnected");
}

void WSServer_NewConnection(EventArgs e)
{
    Console.WriteLine("New connection established");
    WSServer.Send("Hello new client! I hope you enjoy your visit!");
}</pre>
<p>It’s a very simple Web Socket server, so it’s very easy to use. You shouldn’t have much problem understanding it.</p>
<p>Go ahead and download the Visual Studio solution and give it a try!</p>
<p><strong>UPDATE </strong><strong>(October 12th, 2010):</strong></p>
<p><strong>The Web Socket protocol is not closed yet, so it is being constantly updated. This means that previous Web Socket server implementations might stop working after an update has been made to the API. The original version of the code I released here complied with version 75 of the Web Socket draft. The current version is 76, so I updated my code and released a second project.</strong></p>
<p>No idea of what I&#8217;m talking about? I&#8217;ll make it easy for you&#8230; download the v76 implementation first, and if it doesn&#8217;t work then check out the v75 implementation. If you&#8217;re using one of the latest browsers, you should have no trouble.</p>
<p><del><a href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/06/WebSocketsTest.zip" target="_self">WebSocketsTest (draft 75).zip</a></del> (Older browsers)</p>
<p><a title="Web Sockets Test" href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/10/WebSocketsTestdraft76.zip" target="_self"><strong>WebSocketsTest (draft 76).zip</strong></a><strong> (Latest browsers)</strong></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/05/html-5-web-sockets/' rel='bookmark' title='Permanent Link: HTML 5 Web Sockets'>HTML 5 Web Sockets</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET HTTP Handler'>AJAX call using an ASP.NET HTTP Handler</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/feed/</wfw:commentRss>
		<slash:comments>35</slash:comments>
		</item>
		<item>
		<title>HTML 5 Web Sockets</title>
		<link>http://www.undisciplinedbytes.com/2010/05/html-5-web-sockets/</link>
		<comments>http://www.undisciplinedbytes.com/2010/05/html-5-web-sockets/#comments</comments>
		<pubDate>Sun, 30 May 2010 18:07:48 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[HTML 5]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=386</guid>
		<description><![CDATA[Following the series of posts discussing AJAX calls, today we’ll see what is going to be its evolution: Web Sockets. It’s still a very new technology, and support is starting to be implemented in most major browsers and web servers. But don’t count on using it yet, since most of the clients of your web [...]]]></description>
			<content:encoded><![CDATA[<p>Following the <a title="ajax calls" href="http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/" target="_blank">series of posts discussing AJAX calls</a>, today we’ll see what is going to be its <strong>evolution</strong>: Web Sockets. It’s still a very new technology, and support is starting to be implemented in most major browsers and web servers. But don’t count on using it yet, since most of the clients of your web app will not be able to use them. I’ll discuss web sockets here just so you know what the future is going to bring to the web apps world.</p>
<h4>The history: the beginning of AJAX</h4>
<p>The world wide web and the Internet started as a stateless content delivery mechanism, taking a step backwards compared to traditional desktop applications. Early Internet applications needed to explicitly request every piece of information, and the server sent only the requested data.</p>
<p>Then came what we now call “Web 2.0 application development”: Dynamic HTML, heavy usage of JavaScript, AJAX, and various plugins (Adobe Flash and Microsoft Silverlight). These applications were dynamic and responsive, and they brought much of that rich interactive experience users enjoyed in desktop client/server applications to the Internet. However, due to the request and response architecture that these applications are based on, the latest Rich Internet Applications still cannot match the connectivity and the capability to get real-time data that client/server applications had more than a decade ago.</p>
<p><span id="more-386"></span></p>
<p>The reason is that these applications still need to initiate the communication from the web browser to get some data from the server: that is, the client part of the application running in the web browser has no way to know whether the server has some data for it.</p>
<h4>The next logical step: polling and Comet programming techniques</h4>
<p>Thus, software engineers started working in solving this problem. The client needed to be conscious of any request the server might have for it. But how to achieve this? Well, if communication can only be started by the client, then let’s just make it that way. We’ll make the client constantly ask the server whether there’s some data ready for it. This is what is called <strong>polling</strong>.</p>
<p>By using this technique, the web application essentially polls the server on a regular basis, based on a timer, using a simple HTTP request each time the timer expires. However, the cost of polling frequently is very high – both in terms of network bandwidth as well as server infrastructure needed to support a huge number of polling requests. The server must have the capability to buffer the data that it needs to send to the client until the next request comes from the client.</p>
<p>After a short while, this technique was seen totally unusable due to its great resource requirements. Then came the <strong>Comet programming techniques –</strong> long polling and streaming:</p>
<p>In <strong>long polling</strong>, also known as asynchronous polling, the browser sends a request to the server and the server keeps the request open for a set period. If a notification is received within that period, a response containing the message is sent to the client. If a notification is not received within the set time period, the server sends a response to terminate the open request and the browser resends the request to the server.</p>
<p>When <strong>streaming</strong> is used, the browser sends a complete request, but the server sends and maintains an open response that is continuously updated. A request is sent and kept open indefinitely (or for a set period of time) and the response is updated whenever a message is ready to be sent, but the server never signals to complete the response, thus keeping the connection open to deliver future messages.</p>
<p>But if you think about it, these techniques are just <strong>hacks</strong>, <strong>tricks</strong> used to <em><strong>simulate</strong></em> a technology that doesn’t exist: server-sent events. If the server could actually start the communication, none of these ugly tricks would be needed.</p>
<h4>The evolution: server-sent events &amp; Web Sockets</h4>
<p>We had to wait until HTML 5 came to solve this problem. The Communication section in the HTML 5 specification section introduces server-sent events and Web Sockets. These new features enable a new paradigm of web application programming that will revolutionize the way to develop and deploy web applications.</p>
<p>Server-sent events are not quite the solution, but a formalization of Comet programming techniques. The server-sent event HTML 5 specification introduces a new DOM element called <em>eventsource</em>.</p>
<p>But the guy we must pay all our attention to is the HTML 5 Web Socket specification: the Web Socket interface defines a<strong> full duplex communications channel</strong> that is exposed via a JavaScript interface in HTML 5 compliant browsers.</p>
<p>When a new Web Socket connection is established, the browser opens an HTTP connection to the server first and then negotiates with the server to upgrade the connection to a dedicated and persistent Web Socket connection. This process automatically sets up a tunnel through to the server, solving numerous issues that the various Comet programming techniques encountered. Once established the Web Socket is a full duplex channel between the client and the server.</p>
<p>I&#8217;ve developed a Web Socket server and client implementation. <a href="http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/">Check it out</a> for yourself and see what I&#8217;m talking about!</p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/' rel='bookmark' title='Permanent Link: Different ways to use AJAX in ASP.NET'>Different ways to use AJAX in ASP.NET</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/05/html-5-web-sockets/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>AJAX call using ASP.NET Web Services</title>
		<link>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/</link>
		<comments>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 20:17:10 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=382</guid>
		<description><![CDATA[We’ve already seen quite a few ways of performing AJAX calls: web pages, HTTP Handlers and Page Methods. Today we’ll see how to request data from the server using ASP.NET Web Services.
Web Services are a very general model for building applications, and can be implemented for any operation system that supports communication over the Internet. [...]]]></description>
			<content:encoded><![CDATA[<p>We’ve already seen <a href="http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/">quite a few ways of performing AJAX calls</a>: <a href="http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/">web pages</a>, <a href="http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/">HTTP Handlers</a> and <a href="http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/">Page Methods</a>. Today we’ll see how to request data from the server using ASP.NET Web Services.</p>
<p>Web Services are a very general model for building applications, and can be implemented for any operation system that supports communication over the Internet. A Web Service is some programmable application logic accessible via standard Web protocols. It is often referred to as <em>Web APIs </em>as well, since they are a set of methods that provide some functionality through remote method calls. It is a way of <strong>offering some of your functionality to all of the internet</strong>. But, of course, some kind of restrictions and security can be built into your web services, if that’s what you wish.</p>
<p><span id="more-382"></span></p>
<p>As it turns out, the previous article I posted showing how to use Page Methods was also a Web Service: Web Methods are the building blocks of Web Services (a Web Service has many different Web Methods). But it was a very small and simple implementation, intended to return simple data to a small script placed in that same web page. The example we’re going to see follows the same concept, but in a larger way. We’re going to see the basics of how to implement a full-blown Web Service that can be accessed from anywhere on the internet.</p>
<p>This is very handful if you want to develop a collection of methods to be called from anywhere in your application. Imagine you’d like to know in which moment the user logged in to the system: you could write this server method and then make it public as a web service. This way, you’ll have this server functionality available through an AJAX call from anywhere in the application.</p>
<p>Ok, enough theory, now let’s get our hands dirty. Get to the .aspx part of the web page in which you wish to implement your ajax call, and write the HTML code we’ve been using in all our examples:</p>
<pre class="brush:xml">&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
      &lt;h2&gt;AJAX call test page&lt;/h2&gt;
      &lt;button type="button" onclick='ExecuteAJAXCall()'&gt;Get server time&lt;/button&gt;
      &lt;br /&gt;&lt;br /&gt;
      &lt;div id="DataContainer" &gt;&lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;</pre>
<p>We need a button to perform the AJAX call, and an empty DIV to hold the data retrieved from the server. Now, the Javascript code:</p>
<pre class="brush:javascript">&lt;script type="text/javascript"&gt;
    function ExecuteAJAXCall() {
        $.ajax({
            type: "POST",
            url: "AJAXCalls.asmx/GetServerTime",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            success: Callback_AJAXCall
        });
    };

    function Callback_AJAXCall(data) {
        document.getElementById("DataContainer").innerHTML = "The time at the server is: " + data.d;
    };
&lt;/script&gt;</pre>
<p>Note that the first function is invoked when the button is pressed. This function is in charge of performing the AJAX call by using the jQuery framework. This time, this function has changed a bit from other examples. Web Services calls require more parameters to set the communication between client and server up. The content type must be declared as “application/json; charset=utf-8”. And, as with the <a href="http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/">previous Page Method example</a>, server procedures are called using the syntax <code>[page name] + “/” + [method name]</code>.</p>
<p>When the AJAX call returns, we have the usual function that takes care of painting the result on the screen. Note how we need to use the <code>d</code> property to access the data this time.</p>
<p>Now, we need to write the Web Service. The easiest way is to right-click on your project and add a new item from there. Select Web Service, and you’ll get a skeleton from which you can implement the functionality you wish in your web service. For our example, we’ll write this piece of code:</p>
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebServiceAJAXCall
{
    /// &lt;summary&gt;
    /// Summary description for AJAXCalls
    /// &lt;/summary&gt;
    [WebService(Namespace = "http://www.undisciplinedbytes.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class AJAXCalls : System.Web.Services.WebService
    {

        [WebMethod] public string GetServerTime()
        {
            return DateTime.Now.ToString();
        }
    }
}</pre>
<p>As you can see, we’ve only written the code required to return the server date and time. If you compare this example to the previous one where I explained how to implement AJAX calls with page methods, you can see that this is essentially the same thing. It all comes down to using the <code>WebMethod</code> attribute from the <code>System.Web.Services library</code>. However, this example that we’re seeing today is more complete, as it is implemented using a full-blown web service. The objective of this article is not to fully explain ASP.NET Web Services (I’ll leave that to some other post I have in mind), but to explain the very basics to be able to implement and AJAX call using them, so I won’t bother about diving into the details. But keep in mind that <strong>Web Services are much more powerful than this</strong>, and that <a title="Web Services" href="http://en.wikipedia.org/wiki/Web_service" target="_blank">their intention aim much higher</a> than simple AJAX calls.</p>
<p>Here’s the Visual Studio project for you to play with:</p>
<p><a title="Web Service AJAX Call" href="http://en.wikipedia.org/wiki/Web_service" target="_blank">WebServiceAJAXCall.zip</a></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET HTTP Handler'>AJAX call using an ASP.NET HTTP Handler</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/' rel='bookmark' title='Permanent Link: Different ways to use AJAX in ASP.NET'>Different ways to use AJAX in ASP.NET</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>AJAX call using an ASP.NET Page Method</title>
		<link>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/</link>
		<comments>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/#comments</comments>
		<pubDate>Tue, 06 Apr 2010 19:26:09 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=367</guid>
		<description><![CDATA[We’ve already been through AJAX calls using simple web pages and HTTP Handlers. But there’s still more ways to request data from the server. Today we’ll take a look at how to do so using server methods.
ASP.NET allows you to define methods in the code-behind of an ASPX page. This is very helpful in situations [...]]]></description>
			<content:encoded><![CDATA[<p>We’ve already been through AJAX calls using simple web pages and HTTP Handlers. But there’s still more ways to request data from the server. Today we’ll take a look at how to do so using server methods.</p>
<p>ASP.NET allows you to define methods in the code-behind of an ASPX page. This is very helpful in situations where you want to expose some specific server side functionality such as data retrieval for a specific page. If you need to make the operation available to multiple different .aspx pages it’s a better idea to use a web service so your pages can share the functionality. We’ll see how to use web services in the next post.</p>
<p>Please note that page methods must be declared as static, meaning a page method is completely self-contained, and no page controls are accessible through the page method. For example, if you have a textbox on the web form, there is no way the page method can get or set its value. Consequently any changes with regards to the controls have no affect on the page method. It is stateless and it does not carry any of the view-state data typically carried around by an ASP.NET page.</p>
<p><span id="more-367"></span></p>
<p>Ok, so we’ll set up the HTML we need to run this test. We’ll use the same one we’ve been using in all our examples:</p>
<pre class="brush:xml">&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
      &lt;h2&gt;AJAX call test page&lt;/h2&gt;
      &lt;button type="button" onclick='ExecuteAJAXCall()'&gt;Get server time&lt;/button&gt;
      &lt;br /&gt;&lt;br /&gt;
      &lt;div id="DataContainer" &gt;&lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;</pre>
<p>As usual, we’ll draw a button to perform the AJAX call, and an empty DIV to hold the data retrieved from the server. Now, the Javascript call:</p>
<pre class="brush:javascript">&lt;script type="text/javascript"&gt;
    function ExecuteAJAXCall() {
        $.ajax({
            type: "POST",
            url: "default.aspx/GetServerTime",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataType: 'json',
            success: Callback_AJAXCall
        });
    };

    function Callback_AJAXCall(data) {
        document.getElementById("DataContainer").innerHTML = "The time at the server is: " + data.d;
    };
&lt;/script&gt;</pre>
<p>Note that the first function is invoked when the button is pressed. This function is in charge of performing the AJAX call by using the jQuery framework. This time, this function has changed a bit from other examples. Page method AJAX calls require more parameters to set up the communication between client and server. We need to set the content type, and send the parameters to the method, even if it is a parameter-less method. Note how we’re calling the method by using the syntax <code>[page name] + “/” + [method name]</code>.</p>
<p>When the AJAX call returns, we have the usual function that takes care of painting the result on the screen. Note how we need to use the <code>d</code> property to access the data this time.</p>
<p>Now comes the interesting part. As we saw before, we’re programming a serverside method in the same web page to return the data from the server, so we don’t need any more web pages in our project. To implement this functionality, get to the codebehind part of the web page and write this code:</p>
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

namespace PageMethodAJAXCall
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        [WebMethod] public static string GetServerTime()
        {
            return DateTime.Now.ToString();
        }
    }
}</pre>
<p>The secret behind this magic is just the <code>System.Web.Services</code> library we’re importing. This library provides the <code>WebMethod</code> attribute, which can be used in <code>public static</code> methods to indicate they’re to be accessed by remote client calls. Whatever the function returns will be sent to the client. Note how this time we don’t need to serialize the data nor we need to deactivate the cache: everything is taken care of by the Web Services library. You just need to set the <code>WebMethod</code> attribute and return the data you want. Nothing more is required.</p>
<p>I would say this way of performing AJAX calls is the easiest of all. It requires almost no more concepts than what a developer will have from regular programming, and hides much of the complexity. However, it is not the standard way of communicating with the server for controls, plugins and widgets out there, so it is not always possible to use it. But if you’re developing your own web control from scratch or you can tweak the way some other web control requests data, you should consider using this technique. Remember: <strong>keep it simple!</strong></p>
<p>As usual, you can take the Visual Studio project from here and take a look at it:</p>
<p><a title="Page Method AJAX Call Project" href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/04/PageMethodAJAXCall.zip" target="_self">PageMethodAJAXCall.zip</a></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET HTTP Handler'>AJAX call using an ASP.NET HTTP Handler</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/' rel='bookmark' title='Permanent Link: Different ways to use AJAX in ASP.NET'>Different ways to use AJAX in ASP.NET</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AJAX call using an ASP.NET HTTP Handler</title>
		<link>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/</link>
		<comments>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/#comments</comments>
		<pubDate>Tue, 23 Mar 2010 14:56:19 +0000</pubDate>
		<dc:creator>Oliver Mezquita</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[backend]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://www.undisciplinedbytes.com/?p=357</guid>
		<description><![CDATA[We’ve already seen how to perform an AJAX call using just a simple ASP.NET web page. Now we’ll see how to do it with an HTTP handler instead of a web page.
But, what is an HTTP handler? Well, as its names suggests, it is an element that handles HTTP requests. Well, but that’s what an [...]]]></description>
			<content:encoded><![CDATA[<p>We’ve already seen <a href="http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/" target="_blank">how to perform an AJAX call using just a simple ASP.NET web page</a>. Now we’ll see how to do it with an HTTP handler instead of a web page.</p>
<p>But, what is an HTTP handler? Well, as its names suggests, it is an element that <em>handles </em>HTTP requests. Well, but that’s what an .aspx web page does, right? Sure, but in a lengthier, slower and resource-hungrier way. Regular web pages inherit from the <code>System.Web.UI.Page</code> class, which contains a lot of overhead and pre and post-processing in order to make it easier for the programmer to return HTML code to the client performing a request. In other words, the web page class has stuff to make it easier to develop a web page. It’s got some logic, doesn’t it?</p>
<p><span id="more-357"></span></p>
<p>But, what if we don’t want to return a web page? Then we’re just wasting resources in our server, since we’re not to going to use any of the facilities the web page class provides. If what we want to return is not an actual web page, then you should avoid using the <code>System.Web.UI.Page </code>class.</p>
<p>We’ll take a closer look at HTTP handlers in some other post I’m preparing, but for now you should know that they’re more adequate for processing AJAX requests.</p>
<p>This example is quite similar to the <a href="http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/" target="_blank">previous one</a>: the only difference is that the HTTP handler replaces the web page. Except for that, we’ll be doing the same call and using the same javascript code. However, just for clarity’s shake, I’ll be posting all the code involved here.</p>
<p>Ok, so now we’ll get our hands dirty and start doing some work! First, we’ll need some HTML code to draw a simple test page. Start a new Visual Studio Project and get to the newly created page. On the C# codebehind of the new page we won’t be changing anything. Leave everything by default. We’ll be doing our work in the .aspx part. This HTML code should be sufficient for our needs:</p>
<pre class="brush:xml">&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
      &lt;h2&gt;jQuery AJAX call test page&lt;/h2&gt;
      &lt;button type="button" onclick='ExecuteAJAXCall()'&gt;Get server time&lt;/button&gt;
      &lt;br /&gt;&lt;br /&gt;
      &lt;div id="DataContainer" &gt;&lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;</pre>
<p>This is a very simple page. We’ll just have a heading, a button to perform the AJAX call, and an empty DIV to hold the data retrieved from the server. Now we need some actual code to make the AJAX call:</p>
<pre class="brush:javascript">&lt;script type="text/javascript"&gt;
   function ExecuteAJAXCall() {
         $.ajax({
             url: "AJAXRequest.ashx",
             dataType: 'json',
             success: Callback_AJAXCall
         });
   };

   function Callback_AJAXCall(data) {
         document.getElementById("DataContainer").innerHTML = "The time at the server is: " + data;
   };
&lt;/script&gt;</pre>
<p>Note that the first function is invoked when the button is pressed. This function is in charge of performing the AJAX call by using the jQuery framework. We’re passing three parameters to the function: the URL of the element that will get called, they type of data we’re expecting back (JSON in this case) and the javascript function to execute once the data gets back to the client. The jQuery ajax function has <a href="http://api.jquery.com/jQuery.ajax/">many more parameters</a>, but we didn’t need them this time since the example is not very complicated.</p>
<p>The function called when the data is returned is very simple: its only purpose is to take the string returned from the server and write it in the container we previously created for this purpose. Note that the parameter it receives, data, is already a javascript object. The AJAX call returns a simple string from the server, but the jQuery function is smart enough to convert that string to a javascript object and pass it to the function we indicated.</p>
<p>Ok, now we’re getting to the interesting point. Now that we have the test page in place, let’s deal with the AJAX call server-side. The <code>AJAXRequest.ashx </code>HTTP handler is the link between the client web browser and the server. Here we’ll process everything we need and we’ll return a string to the client with the data requested.</p>
<p>So here’s how we program an HTTP handler:</p>
<pre class="brush:csharp">using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;

namespace WebApplication1
{
    ///
    /// Processes AJAX requests
    ///
    public class AJAXRequest : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            JavaScriptSerializer JSSerializer = new JavaScriptSerializer();
            string CurrentDate = DateTime.Now.ToString();

            context.Response.CacheControl = "no-cache";
            context.Response.ContentType = "text/plain";
            context.Response.Write(JSSerializer.Serialize(CurrentDate));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}</pre>
<p>To implement an HTTP handler you just need to implement the <code>System.Web.IHttpHandler</code> interface. You need to provide the desired behaviour to the <code>ProcessRequest</code> method and the  <code>IsReusable</code> property. The first method is the one which actually takes care of processing the HTTP requests and returning the data. The <code>IsReusable</code> property determines whether this instance of HTTP handler can be reused for fulfilling another request of the same type.</p>
<p>This implementation is very simple: it just takes the current date and time from the server, converts it to JSON format and returns it. Note the <code>System.Web.Script.Serialization</code> class we’re importing. This class takes care of converting the object we want to return to JSON format. Note the line in which we deactivate the cache as well. If you don’t do this, the AJAX call will always seem to return the same data, as the web browser will have kept a copy of it the first time it was executed. Most AJAX calls need the cache disabled in order to work properly.</p>
<p>You can download a copy of the Visual Studio project and do some tests to check how it works:</p>
<p><a title="jQuery AJAX HTTP Handler Call Visual Studio Project" href="http://www.undisciplinedbytes.com/wp-content/uploads/2010/03/jQueryAJAXHTTPHandlerCall.zip" target="_self">jQueryAJAXHTTPHandlerCall.zip</a></p>


<h4>Related posts:</h4><p><ol><li><a href='http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-web-page/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET web page'>AJAX call using an ASP.NET web page</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-an-asp-net-page-method/' rel='bookmark' title='Permanent Link: AJAX call using an ASP.NET Page Method'>AJAX call using an ASP.NET Page Method</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/04/ajax-call-using-asp-net-web-services/' rel='bookmark' title='Permanent Link: AJAX call using ASP.NET Web Services'>AJAX call using ASP.NET Web Services</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/02/how-to-make-an-ajax-call-using-jquery-and-asp-net-i/' rel='bookmark' title='Permanent Link: Different ways to use AJAX in ASP.NET'>Different ways to use AJAX in ASP.NET</a></li>
<li><a href='http://www.undisciplinedbytes.com/2010/06/html-5-c-web-sockets-server-and-asp-net-client-implementation/' rel='bookmark' title='Permanent Link: HTML 5 C# Web Sockets server and ASP.NET client implementation'>HTML 5 C# Web Sockets server and ASP.NET client implementation</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.undisciplinedbytes.com/2010/03/ajax-call-using-an-asp-net-http-handler/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

