lesson 10 (object oriented ajax with dojo toolkit)
Post on 24-Mar-2015
140 Views
Preview:
TRANSCRIPT
PHP Programming with HTML, CSS, JavaScript, MySQL, Ajax & jQuery
http://shafiul‐alam.blogspot.com/ Page 1
www.bdjobstraining.com
Lesson: 10 (Object Oriented Ajax with Dojo Toolkit)
Object Oriented JavaScript
JavaScript has strong object-oriented programming capabilities, even though some debates have taken place due to the differences in object-oriented JavaScript compared to other languages.
Object-oriented programming is a programming paradigm that uses abstraction to create models based on the real world. It uses several techniques from previously established paradigms, including modularity, polymorphism, and encapsulation.
Terminology
• Class: Defines the characteristics of the Object. • Object: An Instance of a Class. • Constructor: A method called at the moment of instantiation. • Property: An Object characteristic, such as color. • Method: An Object capability as walk. • Inheritance: A Class can inherit characteristics from another Class. • Encapsulation: A Class defines only the characteristics of the Object; a method defines only how
the method executes. • Abstraction: The conjunction of complex inheritance, methods, and properties of an Object must
be able to simulate a reality model. • Polymorphism: Different Classes might define the same method or property.
Core Objects
JavaScript has several objects included in its core; for example, there are objects like Math, Object, Array, and String. The example below shows how to use the Math object to get a random number by using its random() method.
alert(Math.random());
Custom Objects
The Class: JavaScript is a prototype-based language which contains no class statement, such as is found in C++ or Java. This is sometimes confusing for programmers accustomed to languages with a class statement. Instead, JavaScript uses functions as classes. Defining a class is as easy as defining a function. In the example below we define a new class called Person.
function Person() { }
PHP Programming with HTML, CSS, JavaScript, MySQL, Ajax & jQuery
http://shafiul‐alam.blogspot.com/ Page 2
The Object (Class Instance)
To create a new instance of an object obj we use the statement new obj, assigning the result (which is of type obj) to a variable to access it later.
In the example below we define a class named Person and we create two instances (person1 and person2).
function Person() { } var person1 = new Person(); var person2 = new Person();
The Constructor
The constructor is called at the moment of instantiation (the moment when the object instance is created). The constructor is a method of the class. In JavaScript, the function serves as the constructor of the object; therefore, there is no need to explicitly define a constructor method. Every action declared in the class gets executed at the time of instantiation.
The constructor is used to set the object's properties or to call methods to prepare the object for use. Adding class methods and their definitions occurs using a different syntax described later in this article.
In the example below, the constructor of the class Person displays an alert when a Person is instantiated.
function Person() { alert('Person instantiated'); } var person1 = new Person(); var person2 = new Person();
The Property (object attribute)
Properties are variables contained in the class; every instance of the object has those properties. Properties should be set in the prototype property of the class (function) so that inheritance works correctly.
Working with properties from within the class is done by the keyword this, which refers to the current object. Accessing (reading or writing) a property outside of the class is done with the syntax: InstanceName.Property.
In the example below we define the gender property for the Person class and we define it at instantiation.
function Person(gender) { this.gender = gender; alert('Person instantiated'); } Person.prototype.gender = 'Person Gender'; var person1 = new Person('Male');
PHP Programming with HTML, CSS, JavaScript, MySQL, Ajax & jQuery
http://shafiul‐alam.blogspot.com/ Page 3
var person2 = new Person('Female'); //display the person1 gender alert('person1 is a ' + person1.gender); // person1 is a Male
The methods
Methods follow the same logic as properties; the difference is that they are functions and they are defined as functions. Calling a method is similar to accessing a property, but you add () at the end of the method name, possibly with arguments.
In the example below we define and use the method sayHello() for the Person class.
function Person(gender) { this.gender = gender; alert('Person instantiated'); } Person.prototype.gender = 'Person Gender'; Person.prototype.sayHello = function() { alert ('hello'); } var person1 = new Person('Male'); var person2 = new Person('Female'); // call the Person sayHello method. person1.sayHello(); // hello
Inheritance
A method to create a class as a specialized version of one or more classes (JavaScript only supports single class inheritance). The specialized class is commonly called child, and the other class is commonly called parent. In JavaScript this is accomplished by assigning an instance of the parent class to the child class, and then make the specialization.
In the example below, we define the class Student as a child class of Person. Then we redefine the sayHello() method and add the sayGoodBye() method.
// define the Person Class function Person() {} Person.prototype.walk = function(){}; Person.prototype.sayHello = function(){ alert ('hello'); };
PHP Programming with HTML, CSS, JavaScript, MySQL, Ajax & jQuery
http://shafiul‐alam.blogspot.com/ Page 4
// define the Student class function Student() {} // inherit Person Student.prototype = new Person(); // correct the constructor pointer because it points to Person Student.prototype.constructor = Student; // replace the sayHello method Student.prototype.sayHello = function(){ alert('hi, I am a student'); } // add sayGoodBye method Student.prototype.sayGoodBye = function(){ alert('goodBye'); } var student1 = new Student(); student1.sayHello(); student1.sayGoodBye();
Encapsulation
In the previous example, Student does not need to know how the Person class's walk() method is implemented, but still can use that method; the Student class doesn't need to explicitly define that method unless we want to change it. This is called encapsulation, by which every class inherits the methods of its parent and only needs to define things it wishes to change.
Abstraction
JavaScript Function class inherits from Object class (this demonstrates specialization of the model). and the Function.prototype property is an instance of Object (this demonstrates composition)
var foo = function(){}; alert( 'foo is a Function: ' + (foo instanceof Function) ); alert( 'foo.prototype is an Object: ' + (foo.prototype instanceof Object) );
Polymorphism
Different classes can define methods with the same name; methods are scoped to the class in which they're defined. This is only true when the two classes do not hold a parent-child relation.
Object Oriented Ajax
In AJAX you’re aware of the existence of popular XMLHttpRequest objects, which come in very handy for sending http requests to a given host, without involving page reloads. Since AJAX has become a
PHP Programming with HTML, CSS, JavaScript, MySQL, Ajax & jQuery
http://shafiul‐alam.blogspot.com/ Page 5
powerful technology for boosting Web applications, and certainly offers nice capabilities for making web-based user interfaces look similar to desktop programs, the next example will illustrate an object-based method for creating http requester objects. The constructor function for these objects is listed below:
// define 'requester' object function Requester(file){ this.file=file; this.xmlobj=null; try{ // instantiate object for Mozilla, Nestcape, etc. this.xmlobj=new XMLHttpRequest(); } catch(e){ try{ // instantiate object for Internet Explorer this.xmlobj=new ActiveXObject('Microsoft.XMLHTTP'); } catch(e){ // Ajax is not supported by the browser this.xmlobj=null; } } // define 'getData()" method this.getData=function(){ // if request is completed if(this.xmlobj.readyState==4){ // if status == 200 return file data if(this.xmlobj.status==200){ // get data return this.xmlobj.responseText; } else{ alert('Failed to get response :'+ this.xmlobj.statusText); } } } // assign state handler this.xmlobj.onreadystatechange=function(){this.getData}; // open socket connection this.xmlobj.open('GET',this.file,false); // send request this.xmlobj.send(null); }
As shown above, the “Requester()” constructor function only accepts as an argument, the name of the file to be fetched from the server. This argument, and the XMLHttpRequest objects themselves, are declared
PHP Programming with HTML, CSS, JavaScript, MySQL, Ajax & jQuery
http://shafiul‐alam.blogspot.com/ Page 6
as properties of generic requester objects, and will be used to trigger a synchronous http request to a specific host. With reference to object methods, all requester objects expose the “getData()” method, which is used for fetching the contents of the requested file in a string format.
Ajax Classes
Title: Connection
Namespace: System.Net.Ajax
Description: The main AJAX connection class for connecting to a webpage or xml resource.
Constructor(s) Description Return Value
Connection() Empty Constructor Connection Object
Connection(PageRequests) Constructor filled with System.Net.Ajax.PageRequests class object. Connection Object
Method(s) Description Return Value
GetType() Gets the type of class object. Class Object Name
Init() Internal method for constructor initialization. Constructed Object
Create() Internal method for creating the ActiveX Ajax or XMLHttpRequest object. New Ajax Object
Open() Opens the connection and retrieves the webpage or xml resource. Info Object
Properties Description Return Value
ActiveXObject Gets the current running ActiveX Ajax or XMLHttpRequest object. Ajax Object
PageRequests The PageRequests class containing all the Request Objects.
PageRequests Object
Current The currently working request object. Current Request Object
Title: PageRequests
Namespace: System.Net.Ajax
Description: The PageRequests class for holding an array collection of Request class objects.
Constructor(s) Description Return Value
PHP Programming with HTML, CSS, JavaScript, MySQL, Ajax & jQuery
http://shafiul‐alam.blogspot.com/ Page 7
PageRequests() Empty Constructor PageRequests Object
PageRequests(Request) Constructor filled with System.Net.Ajax.Request PageRequests Object
Method(s) Description Return Value
GetType() Gets the type of class object. Class Object Name
Init() Internal method for constructor initialization. Constructed Object
AddRequest(Request) Adds a Request object to the array collection. Nothing
Properties Description Return Value
Requests The array collection of request objects. Array of Request
Title: Request
Namespace: System.Net.Ajax
Description: The Request class for holding all the properties and parameters for the request.
Constructor(s) Description Return Value
Request() Empty Constructor Request Object
Request(RequestMethod) Constructor filled with System.Net.Ajax.RequestMethod.
Request Object
Request(RequestMethod, URL) Constructor filled with System.Net.Ajax.RequestMethod and URL.
Request Object
Request(RequestMethod, URL, Callback)
Constructor filled with System.Net.Ajax.RequestMethod and URL and Callback Method.
Request Object
Request(RequestMethod, URL, Callback, Async)
Constructor filled with System.Net.Ajax.RequestMethod and URL and Callback Method.
Request Object
Request(RequestMethod, URL, Callback, Async, UserObject)
Constructor filled with System.Net.Ajax.RequestMethod and URL and Callback Method and Async setting and optional UserObject.
Request Object
Method(s) Description Return Value
GetType() Gets the type of class object. Class Object Name
PHP Programming with HTML, CSS, JavaScript, MySQL, Ajax & jQuery
http://shafiul‐alam.blogspot.com/ Page 8
Init() Internal method for constructor initialization. Constructed Object
AddParam(Parameter) Adds a Parameter object to the request object parameter array collection. Nothing
AddParam(Name, Value) Adds a name with value to the request object parameter array collection. Nothing
Properties Description Return Value
Method The HTTP request method GET or POST. string
URL The URL to retrieve. string
Params The parameters to send with the POST. Parameter Object Array
Callback The method to callback when the request is loading and complete.
Method Reference
Async Whether the call should be async or sync. Bool
UserObject An extra free object to send back with the callback method. Any Type
Title: Parameter
Namespace: System.Net.Ajax
Description: The Parameter class for holding a name and value of a post parameter.
Constructor(s) Description Return Value
Parameter() Empty Constructor Parameter Object
Parameter(Name, Value) Constructor filled with a Name and Value. Parameter Object
Method(s) Description Return Value
GetType() Gets the type of class object. Class Object Name
Init() Internal method for constructor initialization. Constructed Object
Properties Description Return Value
Name The parameter name to post. string
Value The parameter value to post. string
PHP Programming with HTML, CSS, JavaScript, MySQL, Ajax & jQuery
http://shafiul‐alam.blogspot.com/ Page 9
Title: Namespace
Namespace: Window.Namespace, Namespace
Description: A custom object for handling the creation of namespaces in javascript.
Method(s) Description Return Value
Register(Name) Registers a namespace for use in javascript. Nothing
Title: RequestMethod
Namespace: System.Net.Ajax
Description: An enumeration for handling the HTTP Method.
Properties Description Return Value
Get For sending a Get HTTP Request. string
Post For sending a Post HTTP Request. string
Object-Oriented AJAX with JavaScript
Creating new objects in JavaScript is straightforward. The code below shows how to create a simple Cat object.
// SimpleObject.html <html> <head> <script type="text/javascript"> var Cat = new Object(); Cat.name = "Socks"; Cat.color = "white"; Cat.formerOwners = new Array("Fred","Abe","Julie"); Cat.meow = function() { alert("Meow"); } </script> <title>Simple Object</title> </head> <body> <a href="javascript:void(0)" onclick="Cat.meow();">Cat Sound</a> </body> </html>
PHP Programming with HTML, CSS, JavaScript, MySQL, Ajax & jQuery
http://shafiul‐alam.blogspot.com/ Page 10
A class is a template used to define the methods and properties of a particular type of object. For example, an Animal class could be used to define methods and properties common to all animals. The following example shows how to define a class and instantiate an object of that class.
//Class.html <html> <head> <script type="text/javascript"> function Animal(NAME,COLOR,OWNERS,SOUND) { this.name = NAME; this.color = COLOR; this.formerOwners = OWNERS; this.communicate = function() { alert(SOUND); } } var Owners = new Array("Fred","Abe","Julie"); var Cat = new Animal("Socks","white",Owners,"meow"); var Dog = new Animal("Spot","brown",Owners,"ruff"); </script> <title>Simple Class</title> </head> <body> <a href="javascript:void(0)" onclick="Cat.communicate();">Cat Sound</a> <a href="javascript:void(0)" onclick="Dog.communicate();">Dog Sound</a> </body> </html>
Built-in objects can be extended with prototypes. This can be a bit dangerous as it may affect code that relies on a specific set of properties in the prototype; however, it also can be useful.
//Validator.js function Validator(FORM) { try { this.form = (typeof FORM == "string") ? document.getElementById(FORM) : FORM; var i=0; while (this.form.nodeName.toLowerCase() != "form" && i < 10) {
PHP Programming with HTML, CSS, JavaScript, MySQL, Ajax & jQuery
http://shafiul‐alam.blogspot.com/ Page 11
this.form = this.form.parentNode; i++; } this.errors = new Array(); if (i >= 10) { throw "Error. Cannot find form element."; } } catch (e) { alert("Error in Validator(): " + e.message); } } Validator.prototype.checkLength=function(NAME,MIN,MAX,MSG) { try { var min = MIN || 1; var max = MAX || 10000; var elem = this._getElem(NAME); var value = elem.value; if (value.length < min || value.length > max) { this.errors.push(MSG); return false; } return true; } catch(e) { alert("Error in Validator() -> checkLength(): " + e.message); return false; } } Validator.prototype.submitForm=function() { try { if (this.errors.length > 0) { var errorMsg = "Please correct the following " + this.errors.length + " error(s):\n"; for (var i=0; i<this.errors.length; i++) { errorMsg += "\n * " + this.errors[i]; }
PHP Programming with HTML, CSS, JavaScript, MySQL, Ajax & jQuery
http://shafiul‐alam.blogspot.com/ Page 12
alert(errorMsg); return false; } else { return true; } } catch(e) { alert("Error in Validator() -> submitForm(): " + e.message); return false; } } Validator.prototype._getElem=function(NAME) { try { var elem = eval("this.form." + NAME); return elem; } catch(e) { alert("Error in Validator() -> _getElem(): " + e.message); }}
//Form.html <html> <head> <title>Form</title> <script type="text/javascript" src="Validator.js"></script> <script type="text/javascript"> function init() { document.getElementById("icForm").onsubmit = validate; document.getElementById("icForm").FirstName.focus(); } function validate(e) { if (!e) e = window.event; var target = e.target || e.srcElement; var validator = new Validator(target); validator.checkLength("FirstName",1,100,"Must include first name."); //Add a line to check that the email is valid. return validator.submitForm(); }
PHP Programming with HTML, CSS, JavaScript, MySQL, Ajax & jQuery
http://shafiul‐alam.blogspot.com/ Page 13
window.onload = init; </script> </head> <body> <form id="icForm"> <div class="FormRow"> <label for="FirstName">First Name:</label> <input id="FirstName" name="FirstName" size="20"/> </div> <div class="FormRow"> <label for="Email">Email:</label> <input id="Email" name="Email" size="30"/> </div> <div class="FormRow" style="margin-left:140px"> <input type="submit" value="Submit"/> </div> </form> </body> </html>
top related