Dive into ExtJs 5 – Class-based approach – Model



Dive into ExtJs 5 – Class-based approach – Model

0 0


DiveInToExtJs5

Presentation about Sencha ExtJs 5

On Github Pencroff / DiveInToExtJs5

Dive into ExtJs 5

Let's talk about new version JavaScript framework Sencha ExtJs 5

Created by Sergii Danilov / @pencroff

Hello, my name is Sergii. I am a web developer. Let's discus today about ExtJs 5. Next => What is Sencha ExtJS?

What is Sencha ExtJS?

Wikipedia: «Ext JS is a pure JavaScript application framework for building interactive web applications using techniques such as Ajax, DHTML and DOM scripting. Originally built as an add-on library extension of YUI by Jack Slocum, Ext JS includes interoperability with jQuery and Prototype.»

Sencha: «Ext JS 5 ships with more than 300 classes. We have more than 2 million developers to date and they come from various backgrounds and locations.»

What is Sencha ExtJS? So. What is ExtJs? This is JavaScript framework that contains all features for client-side development out of the box. ExtJs uses class-based development and as we can see it uses more than 300 classes and has big community with more than 2 million developers. Next => Popularity ExtJS

Popularity ExtJS

Play on Google trends Popularity ExtJS What about popularity? As we can see first version was released in 2007 year and it was the most popular JS framework, until developers got new modern frameworks like Angular, Ember and Backbone. I think ExtJs lost first position, because it is so big and oriented to enterprise applications. But it is still has a big community. Next => Features out of the box

Features out of the box

Class-based development

Application architecture (Backbone.js, AngularJS, Ember.js)

Data manipulation, like Underscore.js, but more

DOM queries (JQuery, Zepto.js)

UI elements (JQuery UI, Kendo UI)

Charts (Highcharts, Chart.js)

Loader (RequireJs, yepnope.js)

Features out of the box ExtJs has a lot of features out of the box that really help in development. As foundation in framework uses Class-based approach. ExtJs helps organise application architecture like AngularJS, Ember.js, Backbone.js. Also it has wide opportunities for data manipulation and dom queries. HTML and CSS are hidden from developers under UI elements and charts. All this features load into browser by internal loader. Next => Class-based approach

Class-based approach

  • Inheritance
  • Overriding
  • Mixins
  • Statics
  • Singleton
Class-based approach Class-based approach allow extend the prototype nature of JavaScript and use OOP inside JS environment. Next => Inheritance

Inheritance

        Ext.define('App.common.proxy.AppRest', {
            extend: 'Ext.data.proxy.Rest',
            alternateClassName: 'Ext.data.AppRestProxy',
            alias: 'proxy.apprest',
            reader: {
                type: 'json',
                rootProperty: 'data',
                totalProperty: 'total'
            }
        });
                        
Inheritance Look at Inheritance example. It's really easy to build a branched hierarchy of classes. Next => Overriding

Overriding

        Ext.define('Jarvus.hotfixes.ext.form.field.Tag.FindRecord', {
            override: 'Ext.form.field.Tag',
            //    compatibility: '5.0.1255',

            findRecord: function(field, value) {
                return this.getStore().findRecord(field, value);
            }
        });
                        

New version still has bugs and this feature use for hotfixes

Overriding Overriding give us very good opportunity update hardcoded value inside application. A few days ago I have updated hardcoded time format inside third party component. Next => Mixins

Mixins

        // Declaration
        Ext.define('CanSing', {
            sing: function() {
                alert("For he's a jolly good fellow...")
            }
        });

        // Using
        Ext.define('Musician', {
            mixins: {
                canSing: 'CanSing'
            },
            sing: function() {
                // delegate singing operation to mixin
                this.mixins.canSing.sing.call(this);
            }
        })
                        
Mixins If you need to blend some duplicate logic that is not depended from data, you can use mixins mechanism. Next => Statics

Statics

        Ext.define('Computer', {
            statics: {
                factory: function(brand) {
                    /* 'this' in static methods refer to the class itself */
                    return new this(brand);
                }
            },
            constructor: function(brand) {
                this._brand = brand;
            }
        });

        var dellComputer = Computer.factory('Dell');
                        
Statics Static section gives us an opportunity to put methods to some type, not to instance. Next => Singleton

Singleton

        Ext.define('Exceptions', {
            singleton: true,
            requires: ['Messages'],
            onRequestException: function (conn, response, request, eOpts) {
                'use strict';
                var exceptionInfo = {
                    Status: response.status + ' - ' + response.statusText,
                    Description: response.responseText
                };
                Messages.showException(exceptionInfo);
            }
        });
                        
Singleton Also in ExtJs5 it is very easy to declare singleton behavior. Next => Data Package

Data Package

  • Model
  • Store
Data Package So, we have finished with basics of ExtJs 5 and let's go to Data Package. Data Package consists of two entities : Model and Storage. Next => Model

Model

  • Fields
  • Proxies
  • Validations
  • Associations
  • Sessions
Model In the Model we can easily declare fields, proxies, validators and associations. Also model supports sessions on the client side. Next => Model example

Model example

        Ext.define('App.model.PostModel', {
            extend: 'Ext.data.Model',
            idProperty: '_id',
            fields: [
                { name: '_id', type: 'string' },
                { name: 'title', type: 'string' },
                { name: 'created', type: 'date' },
                { name: 'published', type: 'boolean' },
                { name: 'tags', type: 'auto' },
                { name: 'locales', type: 'auto' } // complex type
            ],
            proxy: {
                type: 'apprest',
                url: '/api/posts'
            }
        });
                        
Model example Look at example of the model. It extended from base Model type and has fields array and proxy for using some kind of native storage (Server side, Local storage and etc.). Next => Custom type

Custom type

        Ext.define('App.fields.Gender', {
            extend: 'Ext.data.field.String',s
            alias: 'data.field.gender',
            validators: {
                type: 'inclusion',
                list: [ 'female', 'male' ]
            }
        });
                        
Custom type Model supports Boolean, Date, Integer, Number and String field types, but you can declare a custom type. Next => Proxy

Proxy

Server side

  • Direct
  • Ajax
  • JsonP
  • Rest

Client side

  • Memory
  • SessionStorage
  • LocalStorage
  • Sql
Proxy ExtJs has sets of proxies for client and server site. Next => Validators

Validators

        Ext.define('App.model.User', {
            extend: 'Ext.data.Model',
            fields: [
                { name: 'id', type: 'int' },
                { name: 'name', type: 'string' },
                { name: 'gender', type: 'gender' }
            ],
            validators: {
                // Validator type could be: Presence, Length, Range,
                // Format, Inclusion, Exclusion, Email and Custom
                name: [
                    'presence',
                    { type: 'length', min: 7 },
                    { type: 'exclusion', list: ['Bender'] }
                ]
            }
        });
                        
Validations Model has a few predefined types of validators list which could be extended by custom validators. Next => Object validation

Object validation

        var newUser = new App.model.User({
            id: 10,
            name: 'Bender',
            gender: 'robot'
        });

        // run some validation on the new user we just created

        console.log('Is User valid?', newUser.isValid());
                        
Object validation Look at the example of model validation. This model is not valid because name can't be Bender and gender can't be robot. Next => Associations

Associations

  • One to One
  • One to Manny
  • Many to Manny
Associations Models support three kinds of associations: one to one, one to many and many to many. Next => Association example

Association example

        Ext.define('App.model.Person', {
            extend: 'App.model.Base',
            fields: [ 'name' ],
            hasMany: 'Order' // the "entityName" for "App.model.Order" (see below)
        });

        Ext.define('App.model.Order', {
            extend: 'App.model.Base',
            fields: [ 'name' ],
            hasMany: 'OrderItem'
        });
                        
Sandbox Association example There is ‘one to many’ association example. Let's play with it in the sandbox. Next => Store

Store

  • Model
  • Proxies
  • Filter
  • Grouper
  • Sorter
Store Usually in the application we have single models as well as collections of models. Or Storages in ExtJs terminology. Storage supports proxies, filters, groupers and sorters. Next => Store example

Store example

        Ext.define('App.model.PostStore', {
            extend: 'Ext.data.Store',
            model: 'App.model.PostModel',
            storeId: 'PostStore',
            autoLoad: true,
            pageSize: 20,
            proxy: {
                type: 'apprest',
                url: '/api/posts'
            },
            listeners: {
                load: 'onStoreLoad'
            }
        });
                        
Store example Look at example of storage. As you can see it has a model and some options. It supports data pagination out of the box. Next => Application architecture

Application architecture

MVC

or

MVVM

What is better?

Application architecture Next part of ExtJs is application architecture entities. In 4th version support MVC was added and in 5th version they added MVVM. What is better? Next => MVC

MVC

  • M = model + storage
  • V = viewport + UI components
  • C = classic controller from ExtJs 4
MVC It is a good classic pattern, but in real applications we have some overhead in coding logic connected to view. I mean read/write operations. Next => MVVM

MVVM

  • M = model + storage
  • V = viewport + UI components
  • VM = view model
MVVM MVVM pattern devoid of this shortcoming, but viewmodel usually overloaded by application logic. Next => MVVM + VC

MVVM + VC

MVVM + VC ExtJs implemented variation of MVVM with view controller, that contains internal app logic. View Controller and Controller looks very similar, but ViewController are created for every view and traditional Controller can listen across few views. Next => UI elements

UI elements

  • View port & layouts
  • Forms
  • Grids
  • Trees
  • Charts
UI elements ExtJs 5 contains big library of ui components for fast development business applications. Next => Layouts

Layouts

Sandbox Layouts Layouts give us an opportunity to manipulate ui elements position easily. Next => Forms

Forms

Sandbox Forms Also we have a lot of components for creating forms Next => Grids

Grids

Sandbox Grids and grids Next => Trees

Trees

Sandbox Trees or trees. Next => Charts

Charts

Sandbox Charts Charts optimised for touch devices. Next => Browser support

Browser support

Browser support All ui components support a lot of different browsers. Next => Router

Router

        Ext.define('App.root.RootCtrl', {
            extend: 'Ext.app.ViewController',
            routes : {
                ':area/:verb/:id' : {
                    action: 'onNavigateDetails',
                    before: 'beforeNavigateDetails'
                }
            },
            onNavigateDetails: function (area, verb, id) {
                // update viewport by route parameters
            },
            beforeNavigateDetails: function (area, verb, id, action) {
                // validate route parameters
                if (verb !== 'add' && verb !== 'edit') this.redirectTo('404');
                action.resume();
            }
        });
                    
Router The Router class is a new addition to Ext JS 5 that was built to make hash change interpretation very simple in a single page application. Next => Loader

Loader

        Ext.Loader.setConfig({
            disableCaching: false, // Disable _dc parameter
            enabled: true, // dynamic dependency loading
            paths: {
                'Global': 'src/common/Global.js',
                'Messages': 'src/common/Messages.js',
                'Exceptions': 'src/common/Exceptions.js',
                'Request': 'src/common/Request.js',
                'App.common.proxy.AppRest': 'src/common/AppRestProxy.js'
            }
        });
                    
Loader Loader used for resolving object dependencies based on 'require' section. Next => Sencha CMD

Sencha CMD

Sencha CMD Sencha Cmd has a lot of features. From scaffolding a new project, to minifying and deploying your application to production, Sencha Cmd provides a full set of lifecycle management features to compliment your Sencha projects. Next => Pros and Cons

Pros and Cons

+

  • All in one and available out of the box
  • High speed development
  • Cross-browser compatibility
  • Support tablets and touch-screens
  • The extensibility of components
  • JS optimization for deployment
  • Theming
  • Hidden HTML

-

  • It is not free ($3,225.00 for 5 licences)
  • Enterprise orientation
  • Large size of js files (565 kb minified and zipped)
  • Hidden HTML

Do you have any questions?

Sources:

Sergii Danilov / @pencroff github.com/Pencroff