Hi,
as i've promised, i would like to mention few things about the usage of the prototype in object oriented javascript. prototype is a reserved keyword in javascript. Prototype of a class is nothing but a native javascript object, surrounded with bracelets { and contains key value pairs that are seperated with a double point {key:value}. You can access these properties everywhere. Not a big deal isn't it? Let's see some code to understand;
function MyClass(){
this.firstVal = 2;
this.allVals = function(){
alert(this.firstVal+this.secondVal);
}
}
If we run this code as it is, we will get some errors because the secondVal is not defined. You can test like this;
var x = new MyClass();
//we call the function by using paranthesis otherwise it will return the function as string.
x.allVals();
alert(typeof(x.secondVal));
and the result will be "undefined". You can ofcourse add this undefined property manually;
x.secondVal = 2;
x.allVals();
this is going to alert "4" but if you add the property to the instance, it won't be reflected to the other instances. Now notice how i define the properties in the prototype and use them in the constructor;
function Otherclass(){
this.allVals = function(){
//i use this keyword to access the properties in the prototype
alert(this.firstVal+this.secondVal);
}
}
Otherclass.prototype = {
firstVal: 2,
secondVal: 2
}
One important thing, if you add a property to the prototype by using the instance, all instances of the same class will have the same property;
var a = new Otherclass();
var b = new Otherclass();
a.prototype.customVal = "Hello world";
alert(b.customVal);
Because you've added the value to the prototype instead of the instance, now all instances will have the customVal property. Besides that there isn't much advantage of using prototype but this method allows you to keep configuration values clear and seperated. You can also extend the prototype as you wish;
Otherclass.prototype = {
firstVal: 2,
secondVal: 2,
exampleObject: {
firstVal: 5,
secondVal: 10
}
}
var k = new Otherclass();
alert(k.prototype.exampleObject.firstVal);
//or
alert(k.exampleObject.firstVal);
Thanks for reading this. My next article will explain the design patterns of javascript. See you next time!
woensdag 14 juli 2010
woensdag 30 juni 2010
Object Oriented Javascript
Hi People,
because many people ask, i am going to introduce you object oriented javascript. Object Oriented programming is actually the way you think about your application espacially the architecture. All frameworks use object oriented way (except some Java frameworks those use Aspect oriented programming, i will talk about it later.) but why? There are many benefits of object oriented programming but one of the reasons is more important and significant than others in total. Object oriented way of programming allows you write robust scalable applications, with other words if you use object oriented way, no matter how complicated is your application, your code will be clear. This is same for the javascript. In fact javascript's object oriented capabilities are more abstract than some server-side languages like PHP or ASP. PHP has always the same class>function hierarchy. You create an instance and get or set the variables or call the functions but in javascript you can extend your classes in very abstract way. You can create classes in another class and extend your application. The parent class gives you control on child classes and so on. There is one more important reason of using object oriented javascript! Javascript is alive after the execution. Object oriented architecture gives you more control on real time functionality.
A javascript class is just a function and you create an instance with the 'new' keyword.
A javascript class has two important elements, Prototype and Constructor.
1 Constructor: as you might know, java classes have a constructor function too which gets called after the instance is created and has the same name as the class itfself. PHP uses _construct and _destruct keywords for the same functionality. The constructor of javascript is simply it's body.
function MyFirstClass(){
//so everything wrapped in the body of
//MyFirstClass is it's constructor
alert("i am constructor");
}
//Now when i create an instance of MyFirstClass, i will get an alert "i am constructor".
new MyFirstClass();
you can use parameters as well in the constructor.
function MyFirstClass(count){
count++;
alert(count);
}
or define the inner variables with the hand of the parameters. Now see how i use the keyword 'this' in my class to scope the class itself
function MyFirstClass(count){
this.c = parseInt(count);
this.c++;
//now just define a function to get the value of c
this.getC = function(){
alert(this.c);
}
//and i call the function in the constructor
this.getC();
}
//now i am going to asign a variable for the instance and call the function getC again.
var k = new MyFirstClass(5);
//i get the alert in constructor but i will change the variable now and call the function getC again
//you can also call this function statically MyFirstClass.getC(); but it will throw an error since
//the variable c is not defined and the constructor doesn't run in this case
k.c = 10;
k.getC();
//this will alert 10. Notice, the constructor won't run again.
Scope is also an important element of javascript. Once you are out of constructor, you need a reference to access MyFirstClass since the scope is changed. That's why i always define a global variable with the keyword 'var' so the reference is created while the scope is still in the constructor.
function MyFirstClass(count){
//notice the _self variable
var _self = this;
this.c = parseInt(count);
this.c++;
//now just define a function to get the value of c
this.getC = function(){
//now i will just use _self global variable so the function is accessible from outside
alert(_self.c);
}
}
Now you can call the methods from outside of focus. For example event based
... onclick="k.getC();" ...
Ok guys. Next time i will continue with the prototype. See you later!
because many people ask, i am going to introduce you object oriented javascript. Object Oriented programming is actually the way you think about your application espacially the architecture. All frameworks use object oriented way (except some Java frameworks those use Aspect oriented programming, i will talk about it later.) but why? There are many benefits of object oriented programming but one of the reasons is more important and significant than others in total. Object oriented way of programming allows you write robust scalable applications, with other words if you use object oriented way, no matter how complicated is your application, your code will be clear. This is same for the javascript. In fact javascript's object oriented capabilities are more abstract than some server-side languages like PHP or ASP. PHP has always the same class>function hierarchy. You create an instance and get or set the variables or call the functions but in javascript you can extend your classes in very abstract way. You can create classes in another class and extend your application. The parent class gives you control on child classes and so on. There is one more important reason of using object oriented javascript! Javascript is alive after the execution. Object oriented architecture gives you more control on real time functionality.
A javascript class is just a function and you create an instance with the 'new' keyword.
A javascript class has two important elements, Prototype and Constructor.
1 Constructor: as you might know, java classes have a constructor function too which gets called after the instance is created and has the same name as the class itfself. PHP uses _construct and _destruct keywords for the same functionality. The constructor of javascript is simply it's body.
function MyFirstClass(){
//so everything wrapped in the body of
//MyFirstClass is it's constructor
alert("i am constructor");
}
//Now when i create an instance of MyFirstClass, i will get an alert "i am constructor".
new MyFirstClass();
you can use parameters as well in the constructor.
function MyFirstClass(count){
count++;
alert(count);
}
or define the inner variables with the hand of the parameters. Now see how i use the keyword 'this' in my class to scope the class itself
function MyFirstClass(count){
this.c = parseInt(count);
this.c++;
//now just define a function to get the value of c
this.getC = function(){
alert(this.c);
}
//and i call the function in the constructor
this.getC();
}
//now i am going to asign a variable for the instance and call the function getC again.
var k = new MyFirstClass(5);
//i get the alert in constructor but i will change the variable now and call the function getC again
//you can also call this function statically MyFirstClass.getC(); but it will throw an error since
//the variable c is not defined and the constructor doesn't run in this case
k.c = 10;
k.getC();
//this will alert 10. Notice, the constructor won't run again.
Scope is also an important element of javascript. Once you are out of constructor, you need a reference to access MyFirstClass since the scope is changed. That's why i always define a global variable with the keyword 'var' so the reference is created while the scope is still in the constructor.
function MyFirstClass(count){
//notice the _self variable
var _self = this;
this.c = parseInt(count);
this.c++;
//now just define a function to get the value of c
this.getC = function(){
//now i will just use _self global variable so the function is accessible from outside
alert(_self.c);
}
}
Now you can call the methods from outside of focus. For example event based
... onclick="k.getC();" ...
Ok guys. Next time i will continue with the prototype. See you later!
zaterdag 13 maart 2010
Android Phone Tracking
Ladies and gentlemen,
today is the day i introduce my latest Android project "Zhe Eye!".
The application has a BroadcastReceiver which starts the GPS tracking service after boot-up. The service is totally invisible and runs in the background. The BroadcastReceiver listens also for SMS events and sen them to the server.
Features;
today is the day i introduce my latest Android project "Zhe Eye!".
The application has a BroadcastReceiver which starts the GPS tracking service after boot-up. The service is totally invisible and runs in the background. The BroadcastReceiver listens also for SMS events and sen them to the server.
Features;
- Listen the environment from your PC
- Take picture (>1.5)
- Read SMS's
- OpenStreetMap api layer
- Time filter for all tasks and activities
- Date Filter
- Hide/Show layers
- Go to the http://freelancephp.be/user/register/ and choose your username and password
- Go to the http://freelancephp.be/member/index/index/ and login
- Click on "Add target" and register your phone (You will need IMEI number for this. go to the settings>about phone>status for IMEI number)
- Click on "Download APK" and, download the APK, install on your phone and restart your phone. It may take a while till you get the GPS fixed.
- Once the connection is established between de server and your Phone, map will be visible and you can see your location, listen your phone and take pictures.
zondag 7 maart 2010
Android and Augmented Reality I
Hi everybody,
i think in the last decade, one of the most exciting trend in Mobile development world was augmented reality. Today i will try to explain how augmented reality works and how to write your very own augmented reality engine. This article will be in three parts:
android.permission.CAMERA
android.permission.ACCESS_GPS
android.permission.ACCESS_ASSISTED_GPS
android.permission.ACCESS_LOCATION
android.permission.ACCESS_COARSE_LOCATION
android.permission.ACCESS_FINE_LOCATION
But just the camera permission is needed for the first chapter. So there are three important components in our activity. First, surfaceView, second surfaceViewListener and third the camera. We don't have to specify a callback for camera since we never will take a picture. We are going to create a surface, listen it and once the surface is created set the surface as preview display of the camera.
So this is how our activiy will look like;
public class AugmentedReality extends Activity{
private View mainView;
private View appView;
private MyCameraView cv;
@Override
public void onCreate(Bundle savedInstanceState) {
//as eveybody says, this will run first :)
super.onCreate(savedInstanceState);
//the main container for the application. We will overlay two views here
//this element should be defined in the XML file
mainView = findViewById(R.id.main);
//create another transparant view
appView = new View(this.getApplicationContext());
//no background color and resource so the holder of the view will be totally invisible
appView.setBackgroundcolor(0);
appView.setBackgroundResource(0);
//create a local variable for the camerra view
//we will define this class in the activity
cv = new MyCameraView(this.getApplicationContext());
//add it to the main view
mainView.addView(cv);
//now we add the second view so it will take the highest z index automatically
mainView.addView(appView);
}
//now we are outside of onCreate.
//lets define the CameraView
public class MyCameraView extends SurfaceView
{
//lets build the constructor
public CustomCameraView(Context ctx)
{
super(ctx);
//we get the holder
previewHolder = this.getHolder();
//set the type
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//and add the listener which is defined below
previewHolder.addCallback(surfaceHolderListener);
}
}
//now we are going to define the listener
//and trigger the camera preview once the surface is visually created
SurfaceHolder.Callback surfaceHolderListener = new SurfaceHolder.Callback() {
private Camera camera;
public void surfaceCreated(SurfaceHolder holder) {
//so the surface is created, we can open the camera
camera = Camera.open();
Parameters params = camera.getParameters();
//we set the format of the preview
//so it will be encoded
//if you get colored horizontal lines instead of preview
//this is the reason
params.setPreviewFormat(PixelFormat.JPEG);
//we don't have to define the format of the taken picture
//since we are not going to take a picture
//params.setPictureFormat(PixelFormat.JPEG);
//finally setthe new parameters
camera.setParameters(params);
try {
//set the surface where the preview should be displayed
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
//you can add your own function here
//this event is fired when any value of the surface is changed
//for example changing to landscape mode automatically
}
public void surfaceDestroyed(SurfaceHolder arg0)
{
//ok when the application is shutdown, we release the camera
//so other applications can use it too
camera.stopPreview();
camera.release();
}
};
}
}
This code will give us the preview of the camera on a surface. In the next chapter we will dive into sensors and retrieve the needed data like latitude, longitude, azimuth and pitch. Thanks for reading.
i think in the last decade, one of the most exciting trend in Mobile development world was augmented reality. Today i will try to explain how augmented reality works and how to write your very own augmented reality engine. This article will be in three parts:
- The first chapter will cover creating surfaceView, placing the camera preview on the surface and adding one more transparant view on the surface.
- Explanation about getting latitude, longitude, azimuth and pitch and some more information about sensors.
- This chapter covers openGL, calculating the x, y and z indexes of a shape and translate it's 3d position on the camera view.
android.permission.CAMERA
android.permission.ACCESS_GPS
android.permission.ACCESS_ASSISTED_GPS
android.permission.ACCESS_LOCATION
android.permission.ACCESS_COARSE_LOCATION
android.permission.ACCESS_FINE_LOCATION
But just the camera permission is needed for the first chapter. So there are three important components in our activity. First, surfaceView, second surfaceViewListener and third the camera. We don't have to specify a callback for camera since we never will take a picture. We are going to create a surface, listen it and once the surface is created set the surface as preview display of the camera.
So this is how our activiy will look like;
public class AugmentedReality extends Activity{
private View mainView;
private View appView;
private MyCameraView cv;
@Override
public void onCreate(Bundle savedInstanceState) {
//as eveybody says, this will run first :)
super.onCreate(savedInstanceState);
//the main container for the application. We will overlay two views here
//this element should be defined in the XML file
mainView = findViewById(R.id.main);
//create another transparant view
appView = new View(this.getApplicationContext());
//no background color and resource so the holder of the view will be totally invisible
appView.setBackgroundcolor(0);
appView.setBackgroundResource(0);
//create a local variable for the camerra view
//we will define this class in the activity
cv = new MyCameraView(this.getApplicationContext());
//add it to the main view
mainView.addView(cv);
//now we add the second view so it will take the highest z index automatically
mainView.addView(appView);
}
//now we are outside of onCreate.
//lets define the CameraView
public class MyCameraView extends SurfaceView
{
//lets build the constructor
public CustomCameraView(Context ctx)
{
super(ctx);
//we get the holder
previewHolder = this.getHolder();
//set the type
previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
//and add the listener which is defined below
previewHolder.addCallback(surfaceHolderListener);
}
}
//now we are going to define the listener
//and trigger the camera preview once the surface is visually created
SurfaceHolder.Callback surfaceHolderListener = new SurfaceHolder.Callback() {
private Camera camera;
public void surfaceCreated(SurfaceHolder holder) {
//so the surface is created, we can open the camera
camera = Camera.open();
Parameters params = camera.getParameters();
//we set the format of the preview
//so it will be encoded
//if you get colored horizontal lines instead of preview
//this is the reason
params.setPreviewFormat(PixelFormat.JPEG);
//we don't have to define the format of the taken picture
//since we are not going to take a picture
//params.setPictureFormat(PixelFormat.JPEG);
//finally setthe new parameters
camera.setParameters(params);
try {
//set the surface where the preview should be displayed
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
//you can add your own function here
//this event is fired when any value of the surface is changed
//for example changing to landscape mode automatically
}
public void surfaceDestroyed(SurfaceHolder arg0)
{
//ok when the application is shutdown, we release the camera
//so other applications can use it too
camera.stopPreview();
camera.release();
}
};
}
}
This code will give us the preview of the camera on a surface. In the next chapter we will dive into sensors and retrieve the needed data like latitude, longitude, azimuth and pitch. Thanks for reading.
donderdag 4 maart 2010
ExtJS editor grid server side example
Hi,
this is my first post and i want to show some examples about usage of ExtJS grid together with a server-side language like PHP or Ruby.
Editor grid contains three main components.
employers:
id: primary key
name: string
surname: string
address: string
Our class will contain two functions
class EditorGridListener{
/*i assume you have a kind of db class that can handle the queries so this is just a pseudo class, this methods should b defined and included before use. So don't ask me why you get method doesn't exist error.*/
private $yourDbClass;
//we simply create the instance with the $_POST array as parameter
public function __construct($post){
//define the db handler
$this->yourDbClass = new YourDatabaseClass;
//run the function requested and print the result
switch($post["task"]){
case "load":
//if $_POST["task"] equals load run this function
print $this->loadGrid();
break;
case "edit":
//if $_POST["edit"] equals load run this function
print $this->editValue($post["id"], $post["key"], $post["value"]);
break;
}
}
private function loadGrid(){
//we simply take all records and send them to the extjs grid as json object
$records = $this->yourDbClass->toArray("employers");
return json_encode(Array("success"=>true, "root"=>$records));
}
private function editValue($id, $key, $value){
//we update the table and change the $key's value to $value for the row $id
$success = $this->yourDbClass->exec("UPDATE employers SET " . $key . "='" . $value . "' WHERE id=" . $id);
return json_encode(Array("success"=>$success));
}
}
$lstnr = new EditorGridListener($_POST);
Now second part, creating the store:
var employerStore = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
//this is where you send the variables and get a response
url: "your-server-side-code.php"
}),
baseParams:{
/*this parameters will be sent with the request. You can add more values like date: new Date(); to load records belong to specific date*/
task: "load"
},
//reader will decode the response.
reader: new Ext.data.JsonReader({
//we put the records in "root" value of the response json which is an array
root: "root"
}, [{
//you have to map at least one column
name: "id",
mapping: "id"
}, "name", "surname", "address"]
)
});
Now we are creating the editor grid:
var = new Ext.grid.EditorGridPanel({
//we bind employerStore with this grid. so if you reload the store, the grid will be updated too
//this is one of the features of ExtJS i like
ds: employerStore,
//some layout values
autoScroll: true,
autoWidth: true,
height: 290,
//it will start editing after 1 click, default is 2
clicksToEdit: 1,
margins: "0 5 5 5",
//we define here the columns retrieved from the data store
columns:[
/*as you see, each column has it's own editor value so you can use any form element as editor including checkbox. once the user clicks on single cell, it will turn into what is described in the editor property of column with it's value*/
{header: "Name", dataIndex: "name", width: 0.2, editor: new Ext.form.TextField({})},
{header: "Name", dataIndex: "surname", width: 0.2, editor: new Ext.form.TextField({})},
{header: "Name", dataIndex: "address", width: 0.6, editor: new Ext.form.TextField({})}
],
listeners: {
//this will fire when the editing is done and the cell lost the focus
afteredit: function(event){
//event is an object and contains all values we need
Ext.Ajax.request({
//your serverside script. refer the php code above
url: "your-server-side-code.php",
//they are other parameters to call editValue function
params: {
task: "edit",
key: event.field,
value: event.value,
id: event.record.data.id
}
/*every ajax request has two callbacks as usual, success callback and error callback. if the response contains a JSON object and the key success equals to true, this function will be called, and if the value is false, failure function will be called*/
success: function(){
//just reload the store to sync with the actual mysql table
event.grid.store.reload();
},
failure: function(){
/*show an error if anything goes wrong.*/
Ext.Msg.alert("Error", "Something went wrong");
}
});
}
}
});
I hope someone can use this information to build powerfull desktop-like web applications with ExtJS. See you soon.
this is my first post and i want to show some examples about usage of ExtJS grid together with a server-side language like PHP or Ruby.
Editor grid contains three main components.
- Data store: this store loads the records being inserted in ExtJS grid. This component is an instance of Ext.data.Store (You can use Grouppingstore as well)
- Editor Grid: this component shows the records in a grid view. This is an instance of Ext.grid.EditorGridPanel. the difference between a regular grid and an editor grid is, you can specify the xtype of the editor for each column. This editor will fire afteredit event which is only available for an EditorGridPanel instance. There are also few other EditorGridPanel specific events like beforeedit, onchange, etc.
- Server-side class, function, file whatever you like. My example will be a PHP example but the main logic is same for the other languages. First function will receive the post data, change the value in database according to the key that is sent. and return a JSON object as response which contains the parameter success {"success":true} or false and second function will send the data so store can reload itself and update the involved grid.
employers:
id: primary key
name: string
surname: string
address: string
Our class will contain two functions
class EditorGridListener{
/*i assume you have a kind of db class that can handle the queries so this is just a pseudo class, this methods should b defined and included before use. So don't ask me why you get method doesn't exist error.*/
private $yourDbClass;
//we simply create the instance with the $_POST array as parameter
public function __construct($post){
//define the db handler
$this->yourDbClass = new YourDatabaseClass;
//run the function requested and print the result
switch($post["task"]){
case "load":
//if $_POST["task"] equals load run this function
print $this->loadGrid();
break;
case "edit":
//if $_POST["edit"] equals load run this function
print $this->editValue($post["id"], $post["key"], $post["value"]);
break;
}
}
private function loadGrid(){
//we simply take all records and send them to the extjs grid as json object
$records = $this->yourDbClass->toArray("employers");
return json_encode(Array("success"=>true, "root"=>$records));
}
private function editValue($id, $key, $value){
//we update the table and change the $key's value to $value for the row $id
$success = $this->yourDbClass->exec("UPDATE employers SET " . $key . "='" . $value . "' WHERE id=" . $id);
return json_encode(Array("success"=>$success));
}
}
$lstnr = new EditorGridListener($_POST);
Now second part, creating the store:
var employerStore = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
//this is where you send the variables and get a response
url: "your-server-side-code.php"
}),
baseParams:{
/*this parameters will be sent with the request. You can add more values like date: new Date(); to load records belong to specific date*/
task: "load"
},
//reader will decode the response.
reader: new Ext.data.JsonReader({
//we put the records in "root" value of the response json which is an array
root: "root"
}, [{
//you have to map at least one column
name: "id",
mapping: "id"
}, "name", "surname", "address"]
)
});
Now we are creating the editor grid:
var = new Ext.grid.EditorGridPanel({
//we bind employerStore with this grid. so if you reload the store, the grid will be updated too
//this is one of the features of ExtJS i like
ds: employerStore,
//some layout values
autoScroll: true,
autoWidth: true,
height: 290,
//it will start editing after 1 click, default is 2
clicksToEdit: 1,
margins: "0 5 5 5",
//we define here the columns retrieved from the data store
columns:[
/*as you see, each column has it's own editor value so you can use any form element as editor including checkbox. once the user clicks on single cell, it will turn into what is described in the editor property of column with it's value*/
{header: "Name", dataIndex: "name", width: 0.2, editor: new Ext.form.TextField({})},
{header: "Name", dataIndex: "surname", width: 0.2, editor: new Ext.form.TextField({})},
{header: "Name", dataIndex: "address", width: 0.6, editor: new Ext.form.TextField({})}
],
listeners: {
//this will fire when the editing is done and the cell lost the focus
afteredit: function(event){
//event is an object and contains all values we need
Ext.Ajax.request({
//your serverside script. refer the php code above
url: "your-server-side-code.php",
//they are other parameters to call editValue function
params: {
task: "edit",
key: event.field,
value: event.value,
id: event.record.data.id
}
/*every ajax request has two callbacks as usual, success callback and error callback. if the response contains a JSON object and the key success equals to true, this function will be called, and if the value is false, failure function will be called*/
success: function(){
//just reload the store to sync with the actual mysql table
event.grid.store.reload();
},
failure: function(){
/*show an error if anything goes wrong.*/
Ext.Msg.alert("Error", "Something went wrong");
}
});
}
}
});
I hope someone can use this information to build powerfull desktop-like web applications with ExtJS. See you soon.
Abonneren op:
Posts (Atom)