Saturday, 19 April 2014

arguments, classes, json usage in javascript and extjs

The Arguments Keyword

The arguments keyword is an implicit parameter available to functions in JavaScript. It’s an array that is used to access
the function’s parameter list, which basically says you don’t really have to formally declare arguments for a function,
but you can still access the values passed, using the ‘arguments’.
Say you have a method to calculate the sum of all the values passed to a method.

function sum() {
        var sum = 0;
        for (var i = 0; i < arguments.length; i++) {
            sum += arguments[i];
        }
        alert(sum);
    }
   
sum(1, 2, 3); //Alerts 6
sum(10, 20, 30, 40, 50); //Alerts 150

Use of Arguments in Ext JS 4

Ext JS 4 API has many functions defined to accept a number of arguments, but you do not always invoke them by
passing all the arguments. For example, here is a code snippet where I handle the itemclick event for a data grid.
Both lines are valid; the difference lies in the number of arguments you pass to the function.

Ext.getCmp("mygrid").on("itemclick",function(src,record){...});
Ext.getCmp("mygrid").on("itemclick",function(src,record,index){...});

You can call a base class method from the derived class method in Ext JS 4 by writing this.callParent(arguments);

Notice the use of the arguments keyword.

Functions

In JavaScript functions are first class citizens, like classes in OO languages.
You can define a function in the traditional way like this.

function eat(){ alert("Eating"); }

You can invoke the eat() function even before you define it, as shown below.
eat();//alerts Eating

function eat(){alert ("Eating"); }

Though JavaScript is an interpreted language, function definitions are run first, irrespective of where they are placed in the code. So you can invoke a function even before you define it like the eat() function call.

You can also assign a function to a variable like this:
var eat = function(){ alert ("Eating"); }

Though eat is defined to be a variable, you can still invoke it like a normal function call: eat(). But what you have to watch out for is that you cannot invoke the eat() function before defining the variable. The following code will throw an error if the function is declared as an expression.

eat();
//Uncaught TypeError: Property 'eat' of object [object DOMWindow] is not a function

var eat = function(){alert ("Eating"); }

So what’s the use of assigning a function to a variable? You can pass the eat variable as an argument to other function
Functions as arguments
function work(arg){
arg();
}
work(eat);
work(function(){alert ("Coding");});

As shown above, the work() function accepts an argument which can be a reference to another function.
We can then invoke the passed function using the arg() call. A function that accepts another function as an argument is commonly referred as a Higher-order function.

Higher-Order Functions in Ext JS 4

In Ext JS 4 you have plenty of functions that accept other functions as arguments. For example, the function that’s called after the DOM is loaded is:
Ext.onReady(function(){
...
});
Ext.onReady() is a higher order function.

Classes in JavaScript

JavaScript is a functional language. It doesn’t have classes like those in OO languages. You can treat functions as classes, and create objects, by using the new keyword. You can create function objects that you can manipulate and pass around like objects. This feature can be used to write traditional OO code.
Say you want to create a class with variables and methods in JavaScript. Instantiate it just as you would in C# or Java. Let’s create a class Person with name and age attributes and an eat() method.

Person class
function Person(theName,theAge){
this.name = theName; //public variable
this.age = theAge;
this.eat = function(){
alert(this.name + " is eating");
}
}

If you now want to create an object of class Person and invoke its eat() method, you can use the new keyword just as in other OO languages.
var p1 = new Person("ManiKumar",23);
p1.eat(); //alerts ManiKumar is eating
alert(p1.age); // alerts 23
The new keyword creates an object from the Person function and returns a reference to the object. Notice the use of this keyword in the Person class. The this keyword binds a variable to the object that is created. You can treat this keyword like a public variable.

Use of Classes in Ext JS 4

The UI components in Ext JS 4 are available as classes. So if you want to create a button, you actually create an object of Button class like this.

var button = new Ext.button.Button();

Now you know how a Button class would be defined in Ext JS 4. It’s just a function.

JSON

One of the most popular and widely-used features of JavaScript is the JavaScript Object Notation (JSON). It’s used to represent a JavaScript object. It’s also used as a data format like XML. Here’s a JSON object.

var myDetails = {
name:"mani kumar",
address : "hyderabad",
test : function(){
alert("hello " + this.name);
}
};

The myDetails variable is a JSON object with some properties. The formats is an array and test() is a function.

Use of JSON in Ext JS 4

The properties of the UI components that you create in Ext JS 4 are specified in JSON
format. Here is some code that creates a button in Ext JS 4.

var btn = new Ext.button.Button({
text : "Click",
id : "mybutton",
handler : function(){
console.log("Button clicked");
}
});

As you can infer from the code, the button’s attributes like text, handler, id are specified as properties of a JSON object.

Thursday, 20 March 2014

Reference Types and Value Types

Reference Types:

variables store reference to a type.

we will see some scenarios :
scenario1:
        class student
        {
            public int id { get;set;}

        }
//'s1' is a variable of type 'student'
student s1 = new student();
//Assign value of s1 to s2 .(value of s1 is address of student object)
student s2 = s1;
s1.id = 23;
// since s1 and s2 are referring same student object, s1.id and s2.id contains same value.
Console.WriteLine("s1 " + s1.id + "  s2 " + s2.id ); 
o/p : s1 23  s2 23

scenario2:

//'s1' is a variable of type 'student'
student s1 = new student();
//Assign value of s1 to s2 .(value of s1 is address of student object)
student s2 = s1;
s1.id = 34;
//creating second instance of student object.
        s1 = new student();
        s1.id = 23;
// s2 is still referring to old student object, but s1 is now referring new student object, hence s1        and s2 holds 
different values
Console.WriteLine("s1 " + s1.id + "  s2 " + s2.id ); 
o/p : s1 23 s2 34

Value Types:

Variables holds value.
int x1 = 10;
//Assign value of x1 to x2(value of x1 is 4 not the address of 4)
int x2 = x1;
x1 = 23;
// since x2 holds value of x1, even if we initialize x1 value to 23 the value of x2 does not change to 23.
Console.WriteLine(x2);
o/p: 10

Wednesday, 19 March 2014

Sample code which uses Delegates and Without using Delegates

You can think of a delegate type as being a bit like an interface with a single method. It specifies the 
signature of a method, and when you have a delegate instance, you can make a call to it as if it were a
method with the same signature. Delegates provide other features, but the ability to make calls with a
particular signature is the reason for the existence of the delegate concept.

we will see the implementation of calculating two numbers (Addition and Multiplication) using delegates and with out using delegates.


without using Delegate:


without using delegates, we need to create interface and implement that interface in two classes. after that we have to create objects for them and access them using object.methodname.


here is the code for it:

-------------------------------------------------------
namespace WithAndWithoutDelagates
{
    interface calculate1
    {
        int Eval(int a, int b);
       
    }
    class Add:calculate1
    {
        int calculate1.Eval(int a, int b)
        {
            return a + b;
        }
    }

    class Multiply : calculate1

    {
        int calculate1.Eval(int a, int b)
        {
            return a * b;
        }
    }
}

//////////////////////////////////////////////////////////////////////////////

 class Program
    {
static void Main(string[] args)
        {
           Console.WriteLine(DoWork1(new Multiply()));

            Console.WriteLine(DoWork1(new Add()));

            Console.ReadLine();
        }

        static int DoWork1(calculate1 f)

        {
            return f.Eval(20, 30);
         
        }
}

///////////////////////////////////////////////////////////////////////////

using delegates:

No interfaces, no clunky .eval stuff, no object instantiation, just simple function-pointer like usage, for a simple task.

-------------------------------------------------
 class Program
    {
        public delegate int calculate(int x, int y);

        static void Main(string[] args)

        {
            calculate del1 = new calculate(Add);
            calculate del2 = new calculate(Multiply);

   Console.WriteLine(DoWork(del1));

            Console.WriteLine(DoWork(del2));
            Console.ReadLine();
        }

        static int Add(int x, int y) 

        {
            return x+y;
        }

        static int Multiply(int x, int y)

        {
            return x*y;
        }

        static int DoWork(calculate f)

        {           
            var res = f(20, 30);
            return res;
        }

    }

Display a form containing check boxes,combo boxes on button click

Just Copy and Paste this Code..Works like Charm..!

Ext.require([
    'Ext.form.*',
    'Ext.window.Window'
]);

Ext.onReady(function() {
    // The data store containing the list of states
var states = Ext.create('Ext.data.Store', {
    fields: ['abbr', 'name'],
    data : [
        {"abbr":"AL", "name":"Alabama"},
        {"abbr":"AK", "name":"Alaska"},
        {"abbr":"AZ", "name":"Arizona"}
    ]
});

    Ext.create('Ext.Button', {
        text: 'Click',
        handler: function () {        
            Ext.create('Ext.form.Panel', {
        renderTo: Ext.getBody(),
        bodyStyle: 'padding: 5px 5px 0 5px;',
        defaults: {
            xtype: 'textfield',
            anchor: '15%',
         },
        items: [
{
                                xtype: 'checkbox',
                                boxLabel: 'Cricket',
                                name: 'sport',
                                checked: true,
                                inputValue: 'cricket'
                            },
                            {
xtype: 'checkbox',
                                boxLabel: 'TableTennis',
                                name: 'sport',
                                inputValue: 'tt'
                            },
                            {
xtype: 'checkbox',
                                boxLabel: 'Football',
                                name: 'sport',
                                inputValue: 'football'
                            },
{
xtype: 'textfield',
name: 'name',
fieldLabel: 'Name',
allowBlank: false  // requires a non-empty value
                            },
                            {
xtype: 'combo',
fieldLabel:'Division',
name:'division',
queryMode:'local',
store:['A','B','C'],
displayField:'division',
autoSelect:true,
forceSelection:true,
     
                            },
{
xtype: 'combo',
                                fieldLabel: 'Choose State',
store: states,
queryMode: 'local',
displayField: 'name',
valueField: 'abbr'
                            },
{
xtype: 'button',
                                text: 'Click Me',
handler: function() {
alert('Clicked!!');
this.up('form').getForm().submit();
}
                            }
   ]  
    });
        },
        renderTo: Ext.getBody()
    });
 
 
});

Saturday, 27 April 2013

ExtJS: sandbox


open html and write the following code:



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <link rel="stylesheet" type="text/css" href="../../resources/css/ext-all.css" />
    <link rel="stylesheet" type="text/css" href="../shared/example.css" />
    <script type="text/javascript" src="../../bootstrap.js"></script>
    <script type="text/javascript" src="../example-data.js"></script>
    <script type="text/javascript" src="editor.js"> </script>
</head>
<body>

</body>
</html>


open js file and write the following code and name it as editor:


Ext.onReady(function () {

    Ext.widget('panel', {
        itemId: 'code-editor',
        title: 'ExtJS Code Editor',
        width: 800,
        height: 600,
        layout: 'border',
        renderTo: Ext.getBody(),
        items: [
            {
                xtype: 'panel',
                region: 'north',
                layout: 'fit',
                height: 200,
                border: false,
                bodyStyle: 'background-color: transparent;',
                split: true,
                items: [
                    {
                        itemId: 'code',
                     
                        xtype: 'textarea',
                        value: "Ext.create('Ext.panel.Panel', {\r\n" +
                                "    title: 'Hello',\r\n" +
                                "    width: 200, \r\n" +
                                "    height: 100, \r\n" +
                                "    html: '<p>Welcome to Intergraph!!</p>', \r\n" +
                                "    renderTo: 'codeoutput' \r\n" +
                                "});"
                    }
                ],
                buttons: [
                    {
                        text: 'Run Code',
                        handler: function () {
                            var code = this.up('panel').down('#code').getValue();
                            try {
                                new Function(code)();
                            } catch (e) {
                                Ext.Msg.alert('Error', e.message);
                            }
                        }
                    }
                ]
            },
            {
                id: 'codeoutput',
                xtype: 'component',
                autoScroll: true,            
                region: 'center'
            }
        ]
    });
});

ExtJs : insert_using_sync_method_in_strore


var teststore = new Ext.data.Store({model: 'NewUnit'});
                 unitstore.add({
                 Name: Ext.getCmp('create-unit-name').getValue(),
                 VehicleTypeId: Ext.getCmp('create-unit-type').getValue(),
                 VehicleInfo: Ext.getCmp('create-unit-note').getValue(),
                 Enabled: Ext.getCmp('create-unit-active').getValue(),
                 GroupId: Ext.getCmp('create-unit-account').getValue()
                 });
unitstore.sync();

ExtJS class,define,create,override,extend,apply,applyif

NOTE : class name should not contain underscore(-) in it


Ext.Class:

 

            Handles class creation throughout the framework. This is a low level factory that is used by Ext.ClassManager and generally should not be used directly. If you choose to use Ext.Class you will lose out on the namespace, aliasing and depency loading features made available byExt.ClassManager. The only time you would use Ext.Class directly is to create an anonymous class.
If you wish to create a class you should use Ext.define which aliases Ext.ClassManager.create to enable namespacing and dynamic dependency resolution.
                         Ext.Class is the factory and not the superclass of everything



            create( [String name] )

If Ext.Loader is enabled and the class has not been defined yet, it will attempt to load the class via synchronous loading.
For example, all these three lines return the same result:
 // alias
 var window = Ext.create('widget.window', {
     width: 600,
     height: 800,
     ...
 });
 
 // alternate name
 var window = Ext.create('Ext.Window', {
     width: 600,
     height: 800,
     ...
 });
 
 // full class name
 var window = Ext.create('Ext.window.Window', {
     width: 600,
     height: 800,
     ...
 });
 
 // single object with xclass property:
 var window = Ext.create({
     xclass: 'Ext.window.Window', // any valid value for 'name' (above)
     width: 600,
     height: 800,
     ...
 });

          define( String className, Object data, Function createdFn )

 Ext.define('My.awesome.Class', {
     someProperty: 'something',
 
     someMethod: function() {
         alert(s + this.someProperty);
     }
 
     ...
 });
 
 var obj = new My.awesome.Class();
 
 obj.someMethod('Say '); // alerts 'Say something'
To defines an override, include the override property. The content of an override is aggregated with the specified class in order to extend or modify that class. This can be as simple as setting default property values or it can extend and/or replace methods. This can also extend the statics of the class.
One use for an override is to break a large class into manageable pieces.
 
 Ext.define('My.app.Panel', {
     extend: 'Ext.panel.Panel',
     requires: [
         'My.app.PanelPart2',
         'My.app.PanelPart3'
     ]
 
     constructor: function (config) {
         this.callParent(arguments); // calls Ext.panel.Panel's constructor
         //...
     },
 
     statics: {
         method: function () {
             return 'abc';
         }
     }
 });
 
 // File: /src/app/PanelPart2.js
 Ext.define('My.app.PanelPart2', {
     override: 'My.app.Panel',
 
     constructor: function (config) {
         this.callParent(arguments); // calls My.app.Panel's constructor
         //...
     }
 });
Another use of overrides is to provide optional parts of classes that can be independently required. In this case, the class may even be unaware of the override altogether.
 Ext.define('My.ux.CoolTip', {
     override: 'Ext.tip.ToolTip',
 
     constructor: function (config) {
         this.callParent(arguments); // calls Ext.tip.ToolTip's constructor
         //...
     }
 });
The above override can now be required as normal.
 Ext.define('My.app.App', {
     requires: [
         'My.ux.CoolTip'
     ]
 });
Overrides can also contain statics:
 Ext.define('My.app.BarMod', {
     override: 'Ext.foo.Bar',
 
     statics: {
         method: function (x) {
             return this.callParent([x * 2]); // call Ext.foo.Bar.method
         }
     }
 });
IMPORTANT: An override is only included in a build if the class it overrides is required. Otherwise, the override, like the target class, is not included.
             apply( Object object, Object config, [Object defaults] )

 the original objects / arrays is needed, use Ext.Object.merge instead.
applyIf( Object object, Object config )

Copies all the properties of config to object if they don't already exist.
If the environment's native JSON encoding is not being used (USE_NATIVE_JSON is not set, or the environment does not support it), then ExtJS's encoding will be used. This allows the developer to add a toJSON method to their classes which need serializing to return a valid JSON representation of the object.

override( Object target, Object overrides )

Overrides members of the specified target with the given values.

 var panel = new Ext.Panel({ ... });
 
 Ext.override(panel, {
     initComponent: function () {
         // extra processing...
         this.callParent();
     }
 });
If the target is none of these, the overrides are applied to the target using Ext.apply.



The parent class that this class extends. For example:
Ext.define('Person', {
    say: function(text) { alert(text); }
});
 
Ext.define('Developer', {
    extend: 'Person',
    say: function(text) { this.callParent(["print "+text]); }
});