Event in ASP.NET AJAX lib Explained

In ASP.NET AJAX lib, there're 2 important types of events, event for Component (Sys.Component) and event for DOM Element.

Let's revise our old knowledge first.

Component (So, its derived class obtains these characteristics)

  • Has to relation with DOM at all.
  • Has no UI representation (not like Control (derived from Component base class) that has).
  • Encapsulates client codes to reuse it across applications *** this is the purpose of Component that exceeds the original DOM elements. In AJAX lib, DOM elements are represent(encapsulate and enrich, indeed) by Sys.UI.Control base class, which actually derive from Sys.Component. So, Component is not Control, but its super class. Component means AJAX lib can manage that things. Some components you wouldn't see with bare eyes (like timer,etc.). Did you get it?
  • Has Handler (cross-browser) that can bind with client object events.
  • Implement Sys.IDisposable.
  • Can raise the propertyChanged notification event when object property changed.
  • You can access events of that Component using get_ and set_ events.

To manage events of Component, we use Sys.EventHandlerList class. It's a dictionary of client events for a component, with event names as keys and the associated handlers as values. It has 3 methods addHandler, clearHandler, and getHandler. For example, when binding event to Component:

   add_tick: function(handler) {
this.get_events().addHandler('tick', handler); }, remove_tick: function(handler) {
this.get_events().removeHandler('tick', handler); }

 this means anything (any class,whatever) that's derived from Component base class. The very important thing is here:

var h = this.get_events().getHandler('tick');
if (h) h(this, Sys.EventArgs.Empty);

This will execute the handler function h. Remember that this handler belongs this Component. For example, Handler 'tick' (this handler) might be the event that is specified from a page developer outside our authority. We, a component developer, may not know this handler at all. He may want to do some special effects presenting to the user on top of UI layer after the time ticked. Page developer doesn't have an idea what's inside our Component too, he just uses it cluelessly.

On the other hand, event for DOM element, when we attach it to that element we call it event binding to DOM element. For example, I bind 'click' event to my button on the page. When it's clicked, it'll do my handler function. Don't forget that, DOM is not the same as Component. It's just a small subset. Here, it is (complete list of its methods): http://msdn.microsoft.com/en-us/library/bb383775.aspx. I think you're familiar with it, no need to explain much:

//register handler for click event on the expand control
$addHandler(yourElement, 'click', yourHandlerFunction);

$clearHandlers(yourElement);

Note that if this.get_element() that you love returns AJAX lib wrapped up DOM element. So, you can attach it an event like this example as well.

Stay tuned for the very near article. Thanks.

Categories:   AJAX Technology | Javascript | Tip(s)
Actions:   E-mail | del.icio.us | Permalink | Comments (2) | RSS


TestSwarm from Mozilla Labs Launched!

Have you ever got a problem with testing javascript in cross-browser platforms. Moreover, testing javascript in various versions of each browser, Opera, Safari, IE, Firefox, etc, is hard and troublesome. In this case, there are some JS test drivers e.g. Selenium , JSTestDriver . But for today, I'll breifly introduce TestSwarm. TestSwarm, that is now in Alpha state, has been developing to support the jQuery project. It simplifies those testing tasks (in multiple-browserplatforms) and provides tools for manipulating your jQuery project workflow. No more on details. Let's get cracking with its walkthrough video.

The example result from TestSwarm :

 

‘Green’ results are 100% passing,

‘Red’ results have at least one failure,

‘Black’ results include a critical error, and

‘Grey’ results have yet to be run.

So, easy to read, agree?>

 

 

Architecture (from http://wiki.github.com/jeresig/testswarm)

The architecture is as follows:

 

There’s a central server which clients connect to and to which jobs are submitted (this is written in PHP and uses MySQL as a backend).

A client is an instance of the TestSwarm test runner loaded in a browser. One user (e.g. ‘john’) can run multiple clients – and even multiple clients within a single browser. For example you could open 5 tabs in Firefox 3 each with a view of the test runner and would have 5 clients connected.

The test runner is very simple – it’s mostly implemented in JavaScript. It pings the server every 30 seconds asking for a new test suite to run. If there is one it executes it (inside an iframe) and then submits the results back to the central server. If there isn’t a test suite available it just goes back to sleep and waits.

A job is a collection of two things: test suites and browsers. When a project submits a job they specify which test suites to run (it may

only be one test suite – but in the case of jQuery I break apart the main suite into sub-suites for convenience and parallelization) and which browsers you wish to run against.

This ends up generating a bunch of ‘runs’ (a run is one specific browser running one specific test suite). A run can be executed multiple times (the minimum is once). For example a project could say “Make sure this suite is run at least 5 times in Firefox 3.”

 

If you want to try its, you can do that online via : http://testswarm.com

Categories:   Javascript | News
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | RSS


AJAX Autocomplete (Suggestion) on ASP.NET from dictionary file

Hi, It's been a long time since my last post about google map. This time I'm going to talk about AJAX autocomplete function. Let's see a sample from the most famous website i've known.

Good News is, It's very easy and you can do it. Just follow my step. First, I'll explain how it works. Most AJAX Libraries require response from server. Every information you want to retrieve from server must be in form of "response" or "JSON" (JavaScript object just like XML for JavaScript). Our Application here is one of examples that i'm going to show you how to retrieve information from server by Response object. Either ASP.NET or PHP can deal with response. So AJAX Library can be applied to those language. All you need to do's write a JavaScript to retrieve response from the server side

Here's an step of how this "Autocomplete" Thing work

  1. Load JavaScript library, initialize and wait for input from user.
  2. User type in letter. Value's passed by "FORM" request to a page named "Default.aspx".
  3. Default.aspx read dictionary file and response to client in a form of unordered list text.
  4. Browser show suggestion to user. User can choose and the text in textbox's completed.

How Simple! here my example

Start!

1. Declare input and output, input is for input from user(Form Request). And output's string output (<ul><li>first item</li><li>second item</li></ul>).

1 protected void Page_Load(object sender, EventArgs e)
2 {
3 String output = "";
4 String input = Request.Form["paramX"];
5 }

Declare it in Page_Load event of Default.aspx

2. Deal with string with space. I'll split the line into array of word. and suggest only the last word. Always response the former text.

1 if (input != null)
2 {
3 String[] arrayS;
4 arrayS = input.Split(' ');
5 for (int i = 0; i < arrayS.Length - 1; i++)
6 {
7 output += arrayS[i] + " ";
8 }
9 input = arrayS[arrayS.Length - 1];

3. Open an fileStream and read "dict.txt". Compare words in the file with input (last word of array) and response in unordered list string

1 using (FileStream fs = new FileStream(Server.MapPath("dict.txt"), FileMode.Open))
2 {
3 using (StreamReader reader = new StreamReader(fs))
4 {
5 String tmp;
6 Response.Write("<ul>");
7 while (!reader.EndOfStream)
8 {
9 tmp = reader.ReadLine();
10 if (tmp.Length >= input.Length && tmp.Substring(0, input.Length) == input || tmp == input) Response.Write("<li>" + output + tmp + "</li>");
11 }
12 Response.Write("</ul>");
13 }
14 }

4. Now, we've done with Default.aspx. This page'll act as service that response text from dictionary when an AJAX Library tried to request the list of suggested word. Next thing, we'll build a page that'll use an AJAX library called "Script Aculo" which has an Autocomplete built-in function. Here's the source code

1 <html xmlns="http://www.w3.org/1999/xhtml" >
2 <head runat="server">
3 <title></title>
4 <script src="js/prototype.js" type="text/javascript"></script>
5 <script src="js/scriptaculous.js" type="text/javascript"></script>
6 <script src="js/controls.js" type="text/javascript"></script>
7 <style type="text/css">
8 /*
9 div.autocomplete {
10 position:absolute;
11 width:500px;
12 background-color:white;
13 border:1px solid #888;
14 margin:0;
15 padding:0;
16 }*/
17 ul {
18 list-style-type:none;
19 margin:0;
20 padding:0;
21 }
22 ul li:hover { background-color: #ffb;}
23 ul li {
24 list-style-type:none;
25 display:block;
26 margin:0;
27 padding:2px;
28 cursor:pointer;
29 }
30 </style>
31
32 </head>
33 <body>
34 <form id="form1" runat="server">
35 <div>
36 <input type="text" id="autocomplete" name="autocomplete_parameter"/>
37 <div id="autocomplete_choices" style=" height:150px; overflow:auto;"></div>
38 <script type="text/javascript">
39 new Ajax.Autocompleter("autocomplete", "autocomplete_choices", "Default.aspx", {
40 paramName : "paramX" 41 });
42 </script>
43 </div>
44 </form>
45 </body>
46 </html>

First thing, include an AJAX library in <head>. Load Script Aculo From www.script.aculo.us It require PROTOTYPE.JS (another javascript library)

put this into your <head>

<script src="js/prototype.js" type="text/javascript"></script>
<script src="js/scriptaculous.js" type="text/javascript"></script>
<script src="js/controls.js" type="text/javascript"></script>

Include downloaded script into your <head>. Then put input box into your <body>

<input type="text" id="autocomplete" name="autocomplete_parameter"/>
<div id="autocomplete_choices" style=" height:150px; overflow:auto;"></div>

Last thing to do! Put javascript after that.

<script type="text/javascript">
new Ajax.Autocompleter("autocomplete", "autocomplete_choices", "Default.aspx", {
    paramName : "paramX"
});
</script>

As usual! Compare your result here.

Find Direction From Your home to AnyWhere? Put in action

Now we've learned how to put google map into your website. Next big step is how to use Google API efficiently. In this example, i'm going to show you guys how to find direction, show it on map and literary detail about how to get to that position.

Our scenario is : I want to find the way from my home(fake location of cos lol) to Salaya, Central Pinkrao And Siam Centre.

1. From last example see it here or you can find example code and view it source.

2. Let's edit it a little bit. Put new Table. Then put 3 button, new div Tag called "detail".

<table style="width:100%;"> 
<tr>
<td width="800"> 
<input type="button" value="Salaya, Mahidol" /> : <input type="button" value="Central Pinkrao" /> : <input type="button" value="Siam Center" />
</td>
<td>&nbsp;</td> 
<tr> 
<td width="800"> 
<div id="mapCanvas" style="width: 800; height: 600"></div> 
</td> 
<td> 
<div id="detail"></div></td> 
</tr></tr> 
</table> 

I'll give action of these three buttons later.

3. Edit javascript as the example. Put map and direction as global variable. Then add new object called direction = new GDirections(map, detail); To set map path to div called "map", and Detail in div Called "detail".

1 <script language="javascript">
2 var map, direction;
3 function initialize() {
4 map = new GMap2(document.getElementById("mapCanvas"));
5 map.setCenter(new GLatLng(13.734132, 100.411992), 13);
6 map.setUIToDefault(); 7 direction = new GDirections(map, detail);
8 }
9 </script>
4. Now, put new function to control the map. I'll add setLocation() that take an integer as argument, it's used to indicate destination. add following function to your javascript part.
1 function setLocation(x) {
2 direction.clear();
3 var str = "from:13.715539,100.408602 to:";
4 if (x == 1) str += "13.793635,100.326054";
5 else if (x == 2) str += "13.778776,100.47658";
6 else str += "13.747014,100.53443"; 7 direction.load(str);
8 }
notice that i clear the Direction drawed on map first. Then i called method load that take str as argument. str is called query word which must be understood by google API. You can put it in form of "from:" and "to:" follow by other query word such as "New York"(name of places in Thailand usually not working with query, so i put lat and long instead).
5. i modified the buttons to let it pass argument to invoke setLocation(x) as following
<input type="button" onclick="setLocation(1)" value="Salaya, Mahidol" /> : <input type="button" onclick="setLocation(2)" value="Central Pinkrao" /> : <input type="button" onclick="setLocation(3)" value="Siam Center" />

6. Compare your result with this

Wow!!! If you like this one or if you have any question, leave your comment. Thank you! i hope that i'll update this one again soon! haha

Categories:   AJAX Technology | Javascript
Actions:   E-mail | del.icio.us | Permalink | Comments (4) | RSS


Let's Get Started With GOOGLE MAP!!

Finally, we've got our conclusion about what we're going to do this year. And it involve with google map. So better start studying it today shall we?

Today i'm going to talk about how to integrate GOOGLE MAP in your website. And i'm going to explain and guide you how to place marker on your custom map.

1. Sign up Beta Key. Go here. Put your website url in the box below.

2. Copy javascript from example in key page For example

 

3. Now, start writing a simple HTML

 

<html><head>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=true_or_false&amp;key=ABQIAAAAeImax-ZV27pxekFFvP............lFgTumTUvfA6Ng" type="text/javascript"></script>
</head>
<body></body>
</html>

Put script from the key above in the head area. And Edit the From Sensor=true_or_false to Sensor=true

4. After that, in the body. Put Div tag which you want it to be canvas of the map in

<div id="mapCanvas" style="width: 800; height: 600"></div>

5. Put another javascript in HEAD tag. This will be custom thing you're going to add script afterward.

<head>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=true_or_false&amp;key=ABQIAAAAeImax-ZV27pxekFFvP............lFgTumTUvfA6Ng" type="text/javascript"></script>
<script type="text/javascript">
function initialize(){
var map = new GMap2(document.getElementByID("mapCanvas"));
}
</script>
</head>

This function will be called everytimes the body of page loaded. var map = new GMap2(document.getElementByID("mapCanvas")); Will build new GMap Object from library retrieve from Google Website.

6. after map builded. Add Custom code to customize the map. Such as set map center view.

map.setCenter(new GLatLng(13.793697,100.325303), 13);

Set to Latitude and Longtitude using object Called GLatLng with Zoom Level = 13.

7. Add additional function map.setUIToDefault(); to add mouse zooming functionality.

8. Edit BODY Tag to call this function everytimes it start.

<body onload="initialize()" onunload="GUnload()"> Add GUnload to prevent Memory Leak.

9. Now Test It here.

10. You can add custom overlay to map, such as marker or additional information. Then use methed map.addOverlay() method.

map.addOverlay(new GMarker(new GLatLng(13.793635,100.326054)));

now We've got a marker point to our building.

That's All For today. Hope i'm coming up with new thing to update you guy! have Fun with google map Kub

Categories:   Javascript | Tip(s)
Actions:   E-mail | del.icio.us | Permalink | Comments (7) | RSS


 

Tag Cloud