Archive for the ‘JAVASCRIPT’ Category

Javascript scalable applications

Thursday, October 1st, 2009

Today I was flipping through reading one of the presentations by Nicholas Zakas, specifically the “Scalable Javascript Applications Architecture“.  Although not the first thing I read on the subject, I enjoyed the clarity with which Nicholas explains. I will try to record the impressions taken in case anyone can help.

1) Theory of modules

The theory of modules (as Nicholas calls it) tells us that one way to create an application that is scalable and easy to maintain, this should be composed of modules.

What are modules?

A module (in our terms) is one application that is part of a larger structure. Each has a job and only takes care of it.

JavascriptScalableApplications
(See Picture)
(I enjoyed this picture gives a clear picture of the meaning of magnitude).

Code

Core.register("hello-world", function(sandbox){
 // Private Variables
 var strPriv = "Private";

 //  Public Methods
 return {
   init: function(){
     try{
      sandbox.console("start the module");
     } catch(ex) {
      alert("sandbox not found");
     }
   },
   destroy: function(){
    // Destructor
   }
 };
});

Here’s an example of a module that recorded with Core.register() we will see later.
Looking at the form we see that the first parameter informs the module name and the second specifies the functionality of the module. This function receives as parameter sandbox (Also see below).
This feature will return an object with at least two methods init() and destroy() that comprise the options available in the module.
init() will be treated as the builder of the module and will be executed when the module is generated. On the other hand destroy() will be treated as the destroyer of the module running when the module is removed.

Sandbox

In software development environment called the Sandbox to test isolated where the experts on running applications. In this case, practically based on the same and that each of the modules used an isolated environment for other modules.
Code

var Sandbox = function() {
   var strPrivate = "Private";

   return {
     alert: function(str){
       alert(str + strPrivate);
     },
     console: function(str) {
       console.log(str);
     }
 }
};

As we see the Sandbox, this is an element that offers a number of ways in which we interact with the application. For example, could be used to interact with the DOM of the application using a JS framework (or not) could implement a simple version and checked to make Ajax requests or validate forms, …. All this is available from the modules.
This module should only worry about what the Sandbox allowed without worrying about what lies beneath it, thus facilitating the development and functionality of each module.
Example:

// Add method notify () to Sandbox
var Sandbox = function() {
  ....
   notify: function(opt){
     // Checks prior
     // .....
     $("#notify #title").text(opt.title);
     $("#notify #content").html(opt.content);
   }
  ....
};

// Use the method notify () of the Sandbox from the module.
Core.register("hello-world", function(sandbox){
   // Private Variables
   ver ver = "1.0";

   return {
    init: function(){
      try{
        sandbox.notify({
          title: "Hello World v." + ver,
          content: 'This is a <strong>Test</strong>.<br />To demonstrate the use of modules'
        });
      } catch(ex) {
        alert("sandbox not found");
      }
    },
    destroy: function(){
     // Destructor
     }
   };
});

In the example we see that at the start of our module, we call the method notify() from sandbox without worrying about what will make this method.
The method after a series of previous validations, simply add a title and content to an element #notify using jQuery.
Thus, the Sandbox filter made between the module and the framework controlling what this intends to do about our application.

The Core

In the above we have seen a variable Core that seems to be the cornerstone of all this. This is a small script that allows modules to register and associate a new instance of the SandBox to each of them every time you run .

var Core = function(){
   // Private Variable
   var modules = {};

   // Instance Creams
   function createInstance(moduleID){
    var instance = modules[moduleID].creator(new Sandbox(this)),
    name, method;

    if (!debug) {
      for (name in instance){
        method = instance[name];
        if (typeof method == "function") {
          instance[name] = function(name, method) {
            return function(){
              try { return method.apply(this, arguments);    }
              catch(ex) { log(1, name + "(): " + ex.message);    }
            }
          }
        }
      }
    }
  return instance;
 }

 //  Public method
 return {
   register: function(moduleID, creator) {
     modules[moduleID] = {
       creator: creator,
       instance: null
     };
   },
   start: function(moduleID) {
     modules[moduleID].instance = createInstance(moduleID);
     modules[moduleID].instance.init();
   },
   stop: function(moduleID){
     var data = modules[moduleID];
     if (data.instance) {
       data.instance.destroy();
       data.instance = null;
     }
   },
   startAll: function(){
     for (var moduleID in modules) {
       if (modules.hasOwnProperty(moduleID)) {
         this.start(moduleID);
       }
     }
   },
   stopAll: function() {
     for (var moduleID in modules) {
       if (modules.hasOwnProperty(moduleID)) {
         this.stop(moduleID);
       }
     }
   }
 };
}();

As we see it is a small script (this is a base, can be extended depending on the needs of the project) that allows us to build the modules we want for every application.
Example

Core.register("....", function(sandbox){});
Core.register("....", function(sandbox){});
Core.register("....", function(sandbox){});
Core.register("....", function(sandbox){});
...

// Start all modules
Core.startAll();

Let Google host your javascript libraries

Tuesday, September 15th, 2009

GoogleCode

An interesting possibility offered by Google developers use it as a CDN (content distribution network) for open source javascript libraries popular. In practice, this means is that in your web development, instead of going to your server for libraries that use scripting, you can directly reference and use the possibilities offered by this company in its servers.

This provides several advantages are not insignificant:

  • First, the discharge of these libraries will, for the client, probably faster than if you have to get from your server through the Internet. This is Google’s network infrastructure, and that means guarantees.
  • Second, and related to the above, if this is a high traffic website, the audience will surely be allowed infinitely greater than you can offer to another server.
  • Third, if the user has previously visited another site that also use the same library, will benefit from the local cache of the same, because your browser does not again discharged. And in any case, they would be taking advantage of Google’s cache optimizations.
  • fourth, do not consume bandwidth from your provider, although this is negligible. And I mean negligible bandwidth, not the provider ;-)
  • fifth, you can use the libraries from sites hosted somewhere where you could not, or is not easy, upload scripts, as the platform Blogger from which to write.

At this point includes: development frameworks, in all versions available:

  • jQuery
  • jQuery UI
  • Prototype
  • script_aculo_us
  • MooTools
  • Dojo
  • SWFObject
  • Yahoo! User Interface Library (YUI)

If you’re already using Google Ajax libraries (such as the Visualization API, or Google Maps), and get through the charger google.load (), you can also use it to download these frameworks. You can also do so through a direct reference, such as:

?View Code JAVASCRIPT
<script 
src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js">
</script>

Oh, and not worry about changing versions, or anything. Google is committed to live indefinitely all distributions to be published and include updates as they appear.

Finally, and to provide a negative view, some people think that this is one more strategy for Google to get information about users’ browsing, code execution from its servers enable cookies and reading of data that could be used for purposes other than those provided on your website. Still others think it could be a source for the spread of malicious code if someone managed to hack these archives. Obviously not a good idea to use this option if you go to work in local mode, offline.

For more information on how to download and libraries available, you can visit the Developer Guide for Ajax libraries API.

5 ways to use Ajax with jQuery

Tuesday, August 25th, 2009

The people of Nettuts publishes an interesting article on using  jQuery with Ajax. Specifically the 5 ways that jQuery allows us to send asynchronous requests.

  • $.load()
  • $.get()
  • $.post()
  • $.getJSON()
  • $.getScript()

$. load ()

This is the feature I like most about jQuery already makes one of the most common tasks of developing with Ajax is as simple and straightforward as we shall see in this example:

$("#div_links").load("/Main_Page #jq-p-Getting-Started li");

This example brought to the documentation page on jQuery, it manages to launch a request to the URL /Main_Page (usa URL Rewrite) HTML response and take the #jq-p-Getting-Started li and inserted into #div_links
Just great, comfortable and fast.

$. get ()

This is the simple function with which we can launch the server via GET requests Ajax.

$.get("test.cgi", { name: "Venu", time: "7pm" },
  function(data){
    alert("Data Loaded: " + data);
  });

By passing 3 options, 2 of which are options (rather conditional) you can request to launch the file (1) with parameters (2) and treat the response through a callback (3rd).

$. post ()

Like the above, this feature lets you send POST requests using Ajax.

$.post("test.php", { name: "Venu", time: "7pm" },
  function(data){
    alert("Data Loaded: " + data);
  });

As easy as above.

$. getJSON ()

Although the above are able to specify the type of return, the best option is to use this method to obtain the response in JSON evaludada the callback function.

$.getJSON("test.js", { name: "Venu", time: "7pm" }, function(json){
  alert("JSON Data: " + json.users[3].name);
});

Taking into account the browser, the object will use native JSON or use a system based on eval().

$. getScript ()

Although technically not an Ajax request is a request to the server and therefore has a place in the post.

$.getScript("test.js", function(){
  alert("Script loaded and executed.");
});

With this method we can load a file asynchronously using JavaScript and the parameter (2) callback can execute Javascript code that is using the js file that we want to load (1).

Everything you ever wanted to know about JSON

Monday, August 24th, 2009

JSON is short for JavaScript Object Notation and is a way of storing information in an organized and easily accessible.

var wcVenuThomas = {
    "age" : "28",
    "hometown" : "Cochin, Kerala, India",
    "gender" : "male"
};

At first glance you get a very clear and that helps your understanding. In this example we have defined a small JSON object called wcVenuThomas composed of a series of attributes. In this way, we can subsequently use to follow the following structure.

alert("Venu Thomas is " + wcVenuThomas.age );

Functions (not to carry information)

Thanks to the versatility of the variables in JavaScript it is possible to match one of these attributes to a function, creating a method of the object itself:

var wcVenuThomas = {
    "age" : "28",
    "hometown" : "Cochin, Kerala, India",
    "gender" : "male"
    "salute" : function(strString) {
    	alert("hello, " + strString + "! I'm Venu Thomas from " + this.hometown + ", How are you?");
    },
};

Now you can salute() :-D

 var usrName = "John James"
wcVenuThomas.salute(usrName);

As part of the JSON object, we can make use of the attributes from the same method by using this operator.

The functions do not make sense to use JSON as a conveyor of information, so we leave it alone as a curious object notation :-D

Arrays

Another option to the JSON is the ability to insert arrays as attributes and in turn define elements within JSON:

var wcVenuThomas = {
    "age" : "28",
    "hometown" : "Cochin, Kerala, India",
    "gender" : "male"
    "salute" : function(strString) {
    	alert("hello I'm Venu Thomas from " + this.hometown + ", How are you? " + strString + "?");
    },
    "projects":[
    	{
    		"name" : 	"Apple News and Analytics ",
    		"url"		 : 	"http://apple.wisecodes.com"
    	},
    	{
    		"name" :	"Life Style Blog",
    		"url"		 :  "http://telegraph.wisecodes.com"
    	}
    ]
};

In this way we can travel an arrays are:

var projects = wcVenuThomas.projects, html = '';
for (var x = 0 ; x < projects.length ; x++) {
html += '<li><a href="' + projects[x].url + '">' + projects[x].name + '</a></li>';
}

JSON object chaining

Another way of grouping elements is to use JSON JSON objects embedded within other objects JSON:

var wcVenuThomas = {
    "age" : "28",
    "hometown" : "Cochin, Kerala, India",
    "gender" : "male"
    "salute" : function(strString) {
    	alert("hello I'm Venu Thomas from " + this.hometown + ", How are you? " + strString + "?");
    },
    "projects":{
    	"applenews": {
    		"url"		 : 	"http://apple.wisecodes.com"
},
  	  "lifestyleblog": {
    		"url"		 :  "http://telegraph.wisecodes.com"
}
    }
};

As we can see, really the only thing we have done is to insert an object into a JSON attribute father, so we can access it as follows:

var URL = wcVenuThomas.projects.applenews.url;

Practical uses

As data storage system, is ideal for transporting from one page to another, even a website to another. A very simple and is used to obtain data from Flickr using jQuery to get data.

$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
        function(data){
          $.each(data.items, function(i,item){
            $("<img/>").attr("src", item.media.m).appendTo("#images");
            if ( i == 3 ) return false;
          });
        });

In this example, taken from the documentation of jQuery, as we launched a call for the latest images sent to Flickr that have been scheduled with the tag “Cat”. The result will be evaluated and processed to the end to reach us within data, a variable that can go as if we were talking about a variable.

Native JSON

One of the problems encountered with JSON is the assessment of code, since it must be transformed into a variable to use, and this requires the use of eval() which makes the process time is increased considerably .

// Eval
var myObject = eval('(' + myJSONtext + ')');

// Native JSON
var myObject = JSON.parse(myJSONtext);

// Mix
var myObject = (JSON)?JSON.parse(myJSONtext): eval('(' + myJSONtext + ')');

Fortunately, modern browsers (IE8, FF3.5, WebKit, ….) Features are implemented to forget eval() and improve the process time.

Javascript: Tic Tac Toe

Monday, August 10th, 2009

live_preview View Demo downloadDownload Code [3.29 kb]

Playing

The computer always plays with circles ( “O”) and you with blades
( “X”). Start your. To put an X have to click on the button
the bottom panel that corresponds to the position you want to put it. You can
also hand-write it, always with capital letters (without cheating, because the
computer trusts you).

The computer will make its redondel every time you put your X .
Never make a mistake, and if you neglect (and you do not cheat), you win. If you cheat, do not
work correctly.

When the game ends, the computer shows the result and increase the counters
lower. To play another game, press the button again Game , which
Clean the panel game. To clear the counters, click the Clear button Clear.

This < head> between and </head>:

<script language="javascript" type="text/javascript">
// Tic Tac Toe
// Version: 1 (10/08/2009)
// Venu Thomas
// This script and many others can
// download online for free
// in the code: [url = http://www.wisecodes.com] www.wisecodes.com [/ url] 

// To understand the explanations:
// Win - and win puts
// Game - and has put in a two-line 'O' and an empty box
// Defend - keep winning the next move in the opposite
// It makes no sense at first occupy the center if there is victory or play
// There must defend first and attack later. First look for the victory, then
// search and then defends move 

// global variable
var strPlaying = true   

//ROLE PLAY CHECK------------------------------------------------
function wc_fnCheckPlay(grid, record) {
    // check that it is possible to stripe 3 in a row, column or diagonal
     // returns the position where you have to put the record to do so and -1 if there is no gamble   

    var x, y   

    for(x = 0; x < 9; x += 3) {      //Check the rows
        if ((grid.elements[x].value == record) && (grid.elements[x + 1].value == record))
            if (grid.elements[x + 2].value == "")
                return (x + 2)
        if ((grid.elements[x].value == record) && (grid.elements[x + 2].value == record))
            if (grid.elements[x + 1].value == "")
                return (x + 1)
        if ((grid.elements[x + 1].value == record) && (grid.elements[x + 2].value == record))
            if (grid.elements[x].value == "")
                return (x)
    }   

    for(x = 0; x < 3; x++) {     //Check the columns
        if ((grid.elements[x].value == record) && (grid.elements[x + 3].value == record))
            if (grid.elements[x + 6].value == "")
                return (x + 6)
        if ((grid.elements[x].value == record) && (grid.elements[x + 6].value == record))
            if (grid.elements[x + 3].value == "")
                return (x + 3)
        if ((grid.elements[x + 3].value == record) && (grid.elements[x + 6].value == record))
            if (grid.elements[x].value == "")
                return (x)
    }   

    //check the diagonals
    if ((grid.elements[2].value == record) && (grid.elements[4].value == record) && (grid.elements[6].value == ""))
        return (6)
    if ((grid.elements[2].value == record) && (grid.elements[4].value == "") && (grid.elements[6].value == record))
        return (4)
    if ((grid.elements[2].value == "") && (grid.elements[4].value == record) && (grid.elements[6].value == record))
        return (2)
    if ((grid.elements[0].value == record) && (grid.elements[4].value == record) && (grid.elements[8].value == ""))
        return (8)
    if ((grid.elements[0].value == record) && (grid.elements[4].value == "") && (grid.elements[8].value == record))
        return (4)
    if ((grid.elements[0].value == "") && (grid.elements[4].value == record) && (grid.elements[8].value == record))
        return (0)   

    return -1
}   

//HORIZONTAL PARTNER ROLE
function wc_fnPartnerHorizontal(grid, record) {
    // check if it's possible to put 2 in a row, the other empty position ...
     //... same row
     // returns the row to do so, or -1 if not 

    var x, y   

    for(x = 0; x < 9; x += 3) {      //Check the rows
        if ((grid.elements[x].value == record) && (grid.elements[x + 1].value == "") && (grid.elements[x + 2].value == ""))
            return (x)
        if ((grid.elements[x].value == "") && (grid.elements[x + 1].value == record) && (grid.elements[x + 2].value == ""))
            return (x + 1)
        if ((grid.elements[x].value == "") && (grid.elements[x + 1].value == "") && (grid.elements[x + 2].value == record))
            return (x + 2)
    }   

    return -1
}   

//VERTICAL PARTNER ROLE---------------------------------------------------
function wc_fnPartnerVertical(grid, record, playHtal) {
 // check if it's possible to put 2 in a column, the other empty position ...
     //... same column and taking into account whether that position is horizontal pair
     // returns the column if you do not allow horizontal pair, or -1 if not      

    var x, y   

    for(x = 0; x < 3; x++) {         //check the columns
        if ((grid.elements[x].value == record) && (grid.elements[x + 3].value == "") && (grid.elements[x + 6].value == ""))
            if (x != playHtal)        //if partner not interested in horizontal and vertical
                return (x)
        if ((grid.elements[x].value == "") && (grid.elements[x + 3].value == record) && (grid.elements[x + 6].value == ""))
            if ((x + 3) != playHtal)
                return (x + 3)
        if ((grid.elements[x].value == "") && (grid.elements[x + 3].value == "") && (grid.elements[x + 6].value == record))
            if ((x + 6) != playHtal)
                return (x + 6)
    }   

    return -1
}   

//Get POSITION\
function wc_fnGetPosition(playHtal, playVcal) {
 // Find the position that allows you move vertically and horizontally at the same time move
     // known row and column where couples can be

    var x, y, fila, columna
    var position = 0
    matrix = new Array(3)   

    for (x = 0; x < 3; x++) {        //creates a matrix that assigns a row and column position
        matrix[x] = new Array(3)
        for (y = 0; y < 3; y++) {
            matrix[x][y] = position
            position ++
        }
    }   

    for (x = 0; x < 3; x++) {                    //looking for the row and column
        for (y = 0; y < 3; y++) {
            if (matrix[x][y] == playHtal) //find the row
                fila = x
            if (matrix[x][y] == playVcal) //I found the column
                columna = y
        }
    }   

    return (matrix[fila][columna])          //move back position
}   

//FUNCION REDONDELA PUT-------------------------------------------------
function wc_fnPutRedondela(grid) {
    //the ordanador plays

    var play, playHtal, playVcal   

    //attacks and wins
    play = wc_fnCheckPlay(grid, "O")
    if (play != -1) {
        grid.elements[play].value = "O"
        alert('I won!!!')
        document.scoreboard.missing.value++
        strPlaying = false
        return 1
    }   

    //advocates avoiding the rival wins
    play = wc_fnCheckPlay(grid, "X")
    if (play != -1) {
        grid.elements[play].value = "O"
        return 1
    }   

    //attacks and win the next
    playHtal = wc_fnPartnerHorizontal(grid, "O")
    playVcal = wc_fnPartnerVertical(grid, "O", playHtal)
    if ((playHtal != -1) && (playVcal != -1)) {     //you can put 2 and 2 in a row in column
        if ((playHtal != 4) || (playVcal != 4)) {       //is not the center
            play = wc_fnGetPosition(playHtal, playVcal)  //gets where it should put
            grid.elements[play].value = "O"
            return 1
        }
    }   

    //attacks and put two in a row
    if ((playHtal != -1) && (playVcal == -1)) {
        if ((playHtal != 2) && (playHtal != 5) && (playHtal != 8))    //this is arbitrary
            grid.elements[playHtal + 1].value = "O"                        //puts the right
        else
            grid.elements[playHtal - 1].value = "O"                        //placed to the left
        return 1
    }   

    //attacks and put in two column
    if ((playHtal == -1) && (playVcal != -1)) {
        if ((playVcal != 6) && (playVcal != 7) && (playVcal != 8))
            grid.elements[playVcal + 3].value = "O"        //put down
        else
            grid.elements[playVcal - 3].value = "O"        //puts up
        return 1
    }   

    //occupies the center
    if (grid.elements[4].value == "") {
        grid.elements[4].value = "O"
        return 1
    }   

    //This took the first free
    for (x = 0; x < 9; x++)
        if (grid.elements[x].value == "") {
            grid.elements[x].value = "O"
            return 1
        }   

    alert('Draw...')
    document.scoreboard.draw.value++
    strPlaying = false
    return -1
}   

//FUNCION PUT ASPA
function wc_fnPutAspa(grid, position) {   

    //first check that this strPlaying
    if (strPlaying) {
        if (grid.elements[position].value != "")     //empty box
            alert('That box is already occupied.')
        else {                                                  //empty box, you can put
            grid.elements[position].value = "X"  

            //Check if you have won
            if ( wc_fnNotesVictoria(grid, "X") ) {
                alert('Congratulations! You win... :D ')
                document.scoreboard.won.value++
                strPlaying = false
            } else
                wc_fnPutRedondela(grid)
        }
    } else {
        alert('To start a new line \nClick Play again.')
    }
}   

//VICTORIA FUNCTION CHECK
function wc_fnNotesVictoria(grid, record) {   

    //Check if you have earned the record player that plays with  

    var x   

    for(x = 0; x < 9; x += 3) {  //Check the rows
        if ((grid.elements[x].value == record) && (grid.elements[x + 1].value == record) && (grid.elements[x + 2].value == record))
            return true
    }   

    for(x = 0; x < 3; x++) {     //check the columns
        if ((grid.elements[x].value == record) && (grid.elements[x + 3].value == record) && (grid.elements[x + 6].value == record))
            return true
    }   

    //check the diagonals
    if ((grid.elements[2].value == record) && (grid.elements[4].value == record) && (grid.elements[6].value == record))
        return true
    if ((grid.elements[0].value == record) && (grid.elements[4].value == record) && (grid.elements[8].value == record))
        return true   

    return false
}   

</script>

And this from <body> and </body> :

<!-- To display the grid, and Accountants -->
<form name="grid">
  <div align="center"><center>
  <table border="0" width="62%" cellpadding="5">
    <tr>
      <td width="20%"><input type="text" name="T0" size="3"></td>
      <td width="20%"><input type="text" name="T1" size="3"></td>
      <td width="20%"><input type="text" name="T2" size="3"></td>
      <td width="85%" align="right"></td>
    </tr>
    <tr>
      <td width="20%"><input type="text" name="T3" size="3"></td>
      <td width="20%"><input type="text" name="T4" size="3"></td>
      <td width="20%"><input type="text" name="T5" size="3"></td>
      <td width="85%" align="right"></td>
    </tr>
    <tr>
      <td width="20%"><input type="text" name="T6" size="3"></td>
      <td width="20%"><input type="text" name="T7" size="3"></td>
      <td width="20%"><input type="text" name="T8" size="3"></td>
      <td width="85%" align="right"></td>
    </tr>
    <tr>
      <td width="20%"><input type="button" value=" X " name="B0" onClick="wc_fnPutAspa(grid, 0)" class="metal"></td>
      <td width="20%"><input type="button" value=" X " name="B1" onClick="wc_fnPutAspa(grid, 1)" class="metal"></td>
      <td width="20%"><input type="button" value=" X " name="B2" onClick="wc_fnPutAspa(grid, 2)" class="metal"></td>
      <td width="85%"><input type="reset" value="New game" name="new" onClick="strPlaying=true" class="metal"></td>
    </tr>
    <tr>
      <td width="18%"><input type="button" value=" X " name="B3" onClick="wc_fnPutAspa(grid, 3)" class="metal"></td>
      <td width="17%"><input type="button" value=" X " name="B4" onClick="wc_fnPutAspa(grid, 4)" class="metal"></td>
      <td width="18%"><input type="button" value=" X " name="B5" onClick="wc_fnPutAspa(grid, 5)" class="metal"></td>
      <td width="85%"></td>
    </tr>
    <tr>
      <td width="18%"><input type="button" value=" X " name="B6" onClick="wc_fnPutAspa(grid, 6)" class="metal"></td>
      <td width="17%"><input type="button" value=" X " name="B7" onClick="wc_fnPutAspa(grid, 7)" class="metal"></td>
      <td width="18%"><input type="button" value=" X " name="B8" onClick="wc_fnPutAspa(grid, 8)" class="metal"></td>
      <td width="85%" align="right"></td>
    </tr>
  </table>
  </center></div>
</form>

<form name="scoreboard">
  <div align="center"><center>
  <table border="0" width="62%" cellpadding="5" cellspacing="0">
    <tr>
      <td width="20%"><small>draw:<br>
      </small><input type="text" name="draw" value="0" size="6"></td>
      <td width="20%"><small>missing:<br>
      </small><input type="text" name="missing" value="0" size="6"></td>
      <td width="20%"><small>won:<br>
      </small><input type="text" name="won" value="0" size="6"></td>
      <td width="85%"> <br><input type="reset" value="Clear" name="delete" class="metal"></td>
    </tr>
  </table>
  </center></div>
</form>

<h2>Playing</h2>
<p>The computer always plays with <em> circles </em> ( "O") and you with <em> blades </em>
( "X"). Start your. To put an X <em> </em> have to click on the button
the bottom panel that corresponds to the position you want to put it. You can
also hand-write it, always with capital letters (without cheating, because the
computer trusts you).</p>
<p>The computer will make its <em> redondel </em> every time you put your <em> X </em>.
Never make a mistake, and if you neglect (and you do not cheat), you win. If you cheat, do not
work correctly.</p>
<p>When the game ends, the computer shows the result and increase the counters
lower. To play another game, press the button again <strong> Game </strong>, which
Clean the panel game. To clear the counters, click the Clear button <strong>Clear</strong>.</p>

Happy Programming!!! ;)

10 javascript frameworks that need to know

Thursday, August 6th, 2009

Web developers, designers and typesetters should already know JavaScript. The javascript does not know should Wearing batteries to keep the language client for the future (and present).
For those who defend us a little on the subject and we extend our capacity and speed of development can opt to use a framework to give us a lot of options for everyday use.

* SproutCore
* Spry
* JavaScriptMVC
* qooxdoo
* Midori
* Archetype JavaScript Framework
* June Framework
* UIZE
* SimpleJS
* Fleegix.js

Multiline in JavaScript

Thursday, August 6th, 2009

Whenever you try to write a script in Javascript that requires a string of multiple lines get an error code that is poorly trained. That is a problem for these scripts to generate HTML content, because by having a clear line and we lose we do not see exactly what you’re painting.

$('#ID').append(
   '<div id="wcDIV"> \
      <p>Welcome to WiseCodes.Com!</p> \
    </div>'
);

var strWelcome = 'Welcome \
to WiseCodes.Com!'

The key is used (\) to indicate the line, that mysteriously causes the browser detects that it is a single line, making the job of uniting us.
A curiosity of this language that helps us to make things easier and above all clear.

Happy Programming !!! ;-)

The best way to load javascript

Tuesday, August 4th, 2009

Nicholas C. Zakas has been thinking about the issue and has taken 3 points needed to be taken to improve the load javascript on our pages.

* Create two files Javascript. In the first place you need to dynamically load another javascript file and the second with the code needed for our application.
* Javascript includes the first end of the page just above < / body >
* Just below we create a second tag < script > where to call / the file / s needed.

Our HTML would be more or less like this:

<script type="text/javascript" src="http://your.cdn.com/first.js"></script>
<script type="text/javascript">
loadScript("http://your.cdn.com/second.js", function(){
//initialization code
});
</script>

loadScript ()

loadScript () function is responsible for loading the Javascript file in a dynamic and responsible for implementing the code as the second parameter to indicate when it is loaded correctly.

function loadScript(url, callback){

var script = document.createElement("script")
script.type = "text/javascript";

if (script.readyState){  //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else {  //Others
script.onload = function(){
callback();
};
}

script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
}

Clearly, these optimizations improve outcome, although we are talking about milliseconds (or seconds in the worst case). But it’s good to know how to improve our scripts and pulirlos well.

Happy Programming!!! ;)

Doodle.js, library for working with canvas

Friday, July 3rd, 2009

Doodle.js is a library that allows us to easily work with the element <canvas /> and everything that entails. With a similar aesthetic to jQuery, drawing on the canvas that is <canvas /> is as simple as this:


  <head>
  <!--[if IE]><script type="text/javascript" src="http://explorercanvas.googlecode.com/svn/trunk/excanvas.js"></script><![endif]-->
  <script src="./doodle-0.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    function init() {
      (function(oo) {
  oo.canvas('#my_canvas');
  oo.rect({x:25, y:25, width:50, height:50}).draw();

})($doodle);

    };
  </script>
  </head>
  <!--init() is called when the canvas is ready for us.-->
  <body onload="javascript:init();">
    <canvas id="my_canvas" width="600" height="400">
      <p>Fallback: Canvas element is not supported in this browser!</p>
    </canvas>
  </body>

Examples

Do not miss some of the examples available on the homepage of the library:
Spiral multicolor
Rebounds multiple

Detection of faces on canvas with Javascript

Wednesday, June 17th, 2009

Detect faces and is not just for Google Images. Now you can implement it on your website using Javascript and the canvas properties.

Venu

How it works?

To do this we need to work only 2 files in our <head />

<script type="text/javascript" src="dat.js"></script>
<script type="text/javascript" src="detector.js"></script>

Dat.js the file shows how to detect and detector.js the file has the logic of the script can detect faces in any photo.
1 can detect faces in the photos, the process becomes slower depending on what we choose (of course).

1 Face

?View Code JAVASCRIPT
face_detect_one( document.getElementById("myCanvas") );

Multiple Faces

?View Code JAVASCRIPT
face_detect_multi( document.getElementById("myCanvas") , progress_callback, result_callback );
function progress_callback( StepsCompleted, TotalSteps){
....
}

Answer

The response functions that returns the values we obtain a rectangle that contains the person’s face.

?View Code JAVASCRIPT
var myCanvas = document.getElementById("mycanvas");
 
var result = face_detect_one( myCanvas );
if (result) draw_rect(result, myCanvas);
 
function draw_rect(r, myCanvas){
	var CanvasContext = myCanvas.getContext("2d");
 	CanvasContext.strokeRect( r.x, r.y, r.w, r.w );
}

Link: via Percobaan