├── .gitignore
├── demo
├── images
│ ├── plus-circle.png
│ ├── arrow-circle.png
│ ├── cross-circle.png
│ └── disk--pencil.png
├── index.html
├── server.js
└── demo.js
├── Gruntfile.js
├── bower.json
├── package.json
├── README.md
└── WebSocket.js
/.gitignore:
--------------------------------------------------------------------------------
1 | **/*~
2 | node_modules/
3 | bower_components/
4 | .idea
5 |
--------------------------------------------------------------------------------
/demo/images/plus-circle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wilk/Ext.ux.data.proxy.WebSocket/HEAD/demo/images/plus-circle.png
--------------------------------------------------------------------------------
/demo/images/arrow-circle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wilk/Ext.ux.data.proxy.WebSocket/HEAD/demo/images/arrow-circle.png
--------------------------------------------------------------------------------
/demo/images/cross-circle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wilk/Ext.ux.data.proxy.WebSocket/HEAD/demo/images/cross-circle.png
--------------------------------------------------------------------------------
/demo/images/disk--pencil.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wilk/Ext.ux.data.proxy.WebSocket/HEAD/demo/images/disk--pencil.png
--------------------------------------------------------------------------------
/demo/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Ext.ux.data.proxy.WebSocket
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/Gruntfile.js:
--------------------------------------------------------------------------------
1 | module.exports = function (grunt) {
2 | require('load-grunt-tasks')(grunt);
3 |
4 | grunt.initConfig ({
5 | uglify: {
6 | dist: {
7 | files: {
8 | 'WebSocket.min.js': 'WebSocket.js'
9 | }
10 | }
11 | } ,
12 | jshint: {
13 | dist: {
14 | options: {
15 | globals: {
16 | Ext: true
17 | } ,
18 | eqeqeq: true ,
19 | undef: true ,
20 | eqnull: true ,
21 | browser: true ,
22 | smarttabs: true ,
23 | loopfunc: true
24 | } ,
25 | src: ['WebSocket.js']
26 | }
27 | }
28 | });
29 |
30 | grunt.registerTask ('check', ['jshint']);
31 | grunt.registerTask ('minify', ['uglify']);
32 | grunt.registerTask ('build', ['check', 'minify']);
33 | };
34 |
--------------------------------------------------------------------------------
/bower.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Ext.ux.data.proxy.WebSocket",
3 | "version": "1.0.1",
4 | "homepage": "https://github.com/wilk/Ext.ux.data.proxy.WebSocket",
5 | "authors": [
6 | "Vincenzo (Wilk) Ferrari "
7 | ],
8 | "description": "An easy-to-use implementation of the ExtJS/Sencha Touch proxy, using HTML5 WebSocket",
9 | "main": [
10 | "WebSocket.js"
11 | ],
12 | "keywords": [
13 | "sencha",
14 | "extjs",
15 | "senchatouch",
16 | "html5",
17 | "websocket",
18 | "proxy"
19 | ],
20 | "license": "MIT",
21 | "ignore": [
22 | "**/.*",
23 | "package.json",
24 | "node_modules",
25 | "bower.json",
26 | "bower_components",
27 | "test",
28 | "tests",
29 | "ux",
30 | "demo",
31 | "Gruntfile.js"
32 | ],
33 | "dependencies": {
34 | "ext.ux.websocket": "~1.0.0"
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Ext.ux.data.proxy.WebSocket",
3 | "version": "0.0.0",
4 | "description": "An easy-to-use implementation of the ExtJS/Sencha Touch proxy, using HTML5 WebSocket",
5 | "main": "WebSocket.js",
6 | "scripts": {
7 | "test": "echo \"Error: no test specified\" && exit 1"
8 | },
9 | "repository": {
10 | "type": "git",
11 | "url": "https://github.com/wilk/Ext.ux.data.proxy.WebSocket.git"
12 | },
13 | "keywords": [
14 | "extjs",
15 | "sencha",
16 | "senchatouch",
17 | "websocket",
18 | "html5",
19 | "proxy"
20 | ],
21 | "author": "Vincenzo (Wilk)",
22 | "license": "MIT",
23 | "bugs": {
24 | "url": "https://github.com/wilk/Ext.ux.data.proxy.WebSocket/issues"
25 | },
26 | "homepage": "https://github.com/wilk/Ext.ux.data.proxy.WebSocket",
27 | "devDependencies": {
28 | "Faker": "~0.7.0",
29 | "ws": "~0.4.31",
30 | "load-grunt-tasks": "~0.2.1",
31 | "grunt-contrib-uglify": "~0.3.0",
32 | "grunt": "~0.4.2",
33 | "grunt-contrib-jshint": "~0.8.0"
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/demo/server.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var Faker = require('Faker') ,
4 | WSS_PORT = 9001 ,
5 | USER_COUNTER = 10 ,
6 | users = [] ,
7 | WebSocketServer = require('ws').Server;
8 |
9 | console.log('WebSocketServer :: Initializing users table.');
10 | for (var i = 0; i < USER_COUNTER; i++) {
11 | users.push({
12 | id: Faker.Helpers.randomNumber(1000000) ,
13 | age: Faker.Helpers.randomNumber(100) ,
14 | name: Faker.Name.firstName(),
15 | leaf: true
16 | });
17 | }
18 | console.log('WebSocketServer :: Users table initialization done!');
19 |
20 | var wss = new WebSocketServer({port: WSS_PORT}, function (err) {
21 | if (err) {
22 | console.log('Impossible to start the websocket server.');
23 | console.log(err);
24 |
25 | process.exit();
26 | }
27 |
28 | console.log('WebSocketServer :: listening on port ' + WSS_PORT);
29 | });
30 |
31 | wss.broadcast = function (data) {
32 | this.clients.forEach(function (ws) {
33 | ws.send(data);
34 | });
35 | };
36 |
37 | wss.on('connection', function (ws) {
38 | console.log('WebSocket :: connected');
39 |
40 | ws.send(JSON.stringify({
41 | event: 'read' ,
42 | data: {
43 | data: users,
44 | success: true
45 | }
46 | }));
47 |
48 | ws.send(JSON.stringify({
49 | event: 'user/read' ,
50 | data: {
51 | data: users,
52 | success: true
53 | }
54 | }));
55 |
56 | ws.on('message', function (json) {
57 | var message = JSON.parse(json) ,
58 | event = message.event;
59 |
60 | console.log('WebSocket :: event == ' + event);
61 | console.log('WebSocket :: data == ');
62 | console.log(message.data);
63 |
64 | if (event === 'create') {
65 | message.data.forEach(function (user) {
66 | user.id = Faker.Helpers.randomNumber(1000000);
67 | users.push(user);
68 | });
69 |
70 | wss.broadcast(JSON.stringify({
71 | event: 'create' ,
72 | data: {
73 | data: message.data,
74 | success: true
75 | }
76 | }));
77 | wss.broadcast(JSON.stringify({
78 | event: 'user/create' ,
79 | data: {
80 | data: message.data,
81 | success: true
82 | }
83 | }));
84 | }
85 | else if (event === 'read') {
86 | ws.send(JSON.stringify({
87 | event: 'read' ,
88 | data: {
89 | data: users,
90 | success: true
91 | }
92 | }));
93 | ws.send(JSON.stringify({
94 | event: 'user/read' ,
95 | data: {
96 | data: users,
97 | success: true
98 | }
99 | }));
100 | }
101 | else if (event === 'update') {
102 | message.data.forEach(function (user) {
103 | var index = -1;
104 | users.forEach(function (usr, idx) {
105 | if (usr.id === user.id) {
106 | index = idx;
107 | return false;
108 | }
109 | });
110 |
111 | if (index !== -1) users[index] = user;
112 | });
113 |
114 | wss.broadcast(JSON.stringify({
115 | event: 'update' ,
116 | data: {
117 | data: message.data,
118 | success: true
119 | }
120 | }));
121 | wss.broadcast(JSON.stringify({
122 | event: 'user/update' ,
123 | data: {
124 | data: message.data,
125 | success: true
126 | }
127 | }));
128 | }
129 | else if (event === 'destroy') {
130 | message.data.forEach(function (user) {
131 | var index = -1;
132 | users.forEach(function (usr, idx) {
133 | if (usr.id === user.id) {
134 | index = idx;
135 | return false;
136 | }
137 | });
138 |
139 | if (index !== -1) users.splice(index, 1);
140 | });
141 |
142 | wss.broadcast(JSON.stringify({
143 | event: 'destroy' ,
144 | data: {
145 | data: message.data,
146 | success: true
147 | }
148 | }));
149 | wss.broadcast(JSON.stringify({
150 | event: 'user/destroy' ,
151 | data: {
152 | data: message.data,
153 | success: true
154 | }
155 | }));
156 | }
157 | });
158 | });
--------------------------------------------------------------------------------
/demo/demo.js:
--------------------------------------------------------------------------------
1 | Ext.Loader.setConfig({
2 | enabled: true,
3 | paths: {
4 | 'Ext.ux.WebSocket': '../bower_components/ext.ux.websocket/WebSocket.js',
5 | 'Ext.ux.data.proxy.WebSocket': '../WebSocket.js'
6 | }
7 | });
8 |
9 | Ext.require(['Ext.ux.data.proxy.WebSocket']);
10 |
11 | Ext.onReady(function () {
12 | Ext.define('model', {
13 | extend: 'Ext.data.Model',
14 | fields: ['id', 'name', 'age'],
15 | proxy: {
16 | type: 'websocket',
17 | storeId: 'myStore',
18 | url: 'ws://localhost:9001',
19 | reader: {
20 | type: 'json',
21 | rootProperty: 'data'
22 | },
23 | writer: {
24 | type: 'json',
25 | writeAllFields: true
26 | }
27 | }
28 | });
29 |
30 | var store = Ext.create('Ext.data.Store', {
31 | model: 'model',
32 | storeId: 'myStore'
33 | });
34 |
35 | var grid = Ext.create('Ext.grid.Panel', {
36 | renderTo: Ext.getBody(),
37 | title: 'WebSocketed Grid',
38 | width: 500,
39 | height: 300,
40 | store: store,
41 |
42 | selType: 'rowmodel',
43 | selModel: 'rowmodel',
44 | plugins: [Ext.create('Ext.grid.plugin.CellEditing', {
45 | clicksToEdit: 1
46 | })],
47 |
48 | columns: [
49 | {
50 | xtype: 'rownumberer'
51 | } ,
52 | {
53 | text: 'ID',
54 | dataIndex: 'id',
55 | hidden: true
56 | } , {
57 | text: 'Name',
58 | dataIndex: 'name',
59 | flex: 1,
60 | editor: {
61 | xtype: 'textfield'
62 | }
63 | } ,{
64 | text: 'Age',
65 | dataIndex: 'age',
66 | editor: {
67 | xtype: 'numberfield'
68 | }
69 | }],
70 |
71 | tbar: {
72 | xtype: 'toolbar',
73 | defaultType: 'button',
74 | items: [{
75 | text: 'Create',
76 | icon: 'images/plus-circle.png',
77 | handler: function (btn) {
78 | store.insert(0, {});
79 | }
80 | } , '-' , {
81 | text: 'Read',
82 | icon: 'images/arrow-circle.png',
83 | handler: function (btn) {
84 | store.load();
85 | }
86 | } , '-' , {
87 | text: 'Update',
88 | icon: 'images/disk--pencil.png',
89 | handler: function (btn) {
90 | store.sync({
91 | success: function () {
92 | store.load();
93 | }
94 | });
95 | }
96 | } , '-' , {
97 | text: 'Destroy',
98 | icon: 'images/cross-circle.png',
99 | handler: function (btn) {
100 | store.remove(grid.getSelectionModel().getSelection());
101 | }
102 | }]
103 | }
104 | });
105 |
106 | var chart = Ext.create('Ext.chart.Chart', {
107 | renderTo: Ext.getBody(),
108 | title: 'WebSocketed Chart',
109 | width: 500,
110 | height: 300,
111 | store: store,
112 |
113 | axes: [{
114 | type: 'category',
115 | position: 'bottom',
116 | fields: ['name']
117 | } , {
118 | type: 'numeric',
119 | position: 'left',
120 | minimum: 0,
121 | fields: ['age']
122 | }],
123 |
124 | series: [{
125 | type: 'bar',
126 | axis: 'left',
127 | xField: 'name',
128 | yField: 'age'
129 | }]
130 | });
131 |
132 | Ext.define('TreeModel', {
133 | extend: 'Ext.data.Model',
134 | fields: [{
135 | name: 'text',
136 | mapping: 'name',
137 | type: 'string'
138 | } , {
139 | name: 'leaf',
140 | type: 'boolean'
141 | }]
142 | });
143 |
144 | var treeStore = Ext.create('Ext.data.TreeStore', {
145 | storeId: 'myTreeStore',
146 | autoLoad: false,
147 | model: 'TreeModel',
148 | proxy: {
149 | type: 'websocket',
150 | url: 'ws://localhost:9001',
151 | storeId: 'myTreeStore',
152 | api: {
153 | create: 'user/create',
154 | read: 'user/read',
155 | update: 'user/update',
156 | destroy: 'user/destroy'
157 | },
158 | reader: {
159 | type: 'json',
160 | rootProperty: 'data'
161 | }
162 | },
163 | root: {
164 | expanded: true
165 | }
166 | });
167 |
168 | var tree = Ext.create('Ext.tree.Panel', {
169 | renderTo: Ext.getBody(),
170 | title: 'WebSocketed Tree Panel',
171 | width: 500,
172 | height: 300,
173 | store: treeStore
174 | });
175 | });
176 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Ext.ux.data.proxy.WebSocket
2 |
3 | # This library is no longer mainteined.
4 |
5 | Ext.ux.data.proxy.WebSocket is an easy-to-use implementation of the ExtJS/Sencha Touch proxy, using [**Ext.ux.WebSocket**](https://github.com/wilk/ExtJS-WebSocket) (a HTML5 WebSocket wrapper built for ExtJS and Sencha Touch).
6 |
7 | ## Dependencies
8 | * [`Ext.ux.WebSocket`](https://github.com/wilk/ExtJS-WebSocket)
9 |
10 | ## ExtJS 5
11 | The new version of ExtJS 5 has requested to make a new major version of `Ext.ux.data.proxy.WebSocket`.
12 | Now, this new major version **v1.0.0** is located on the master branch.
13 |
14 | ## ExtJS 4 & Sencha Touch 2
15 | It's possible to work either with ExtJS 4 and Sencha Touch 2 with previous version **v0.0.7**
16 |
17 | ## Install via Bower
18 | First of all, install [**Bower**](http://bower.io/).
19 |
20 | Then install the `Ext.ux.data.proxy.WebSocket` dependency (version v1.x.x for ExtJS 5):
21 |
22 | ```bash
23 | $ bower install ext.ux.data.proxy.websocket
24 | ```
25 |
26 | Or install the `Ext.ux.data.proxy.WebSocket` dependency (version v0.0.7 for ExtJS 4 & Sencha Touch 2):
27 |
28 | ```bash
29 | $ bower install ext.ux.data.proxy.websocket#0.0.7
30 | ```
31 |
32 | Now, you got the extension at the following path: *YOUR_PROJECT_PATH/bower_components/ext.ux.data.proxy.websocket/*
33 |
34 | It contains **WebSocket.js**.
35 |
36 | Let's setup the **Ext.Loader** to require the right file:
37 |
38 | ```javascript
39 | Ext.Loader.setConfig ({
40 | enabled: true ,
41 | paths: {
42 | 'Ext.ux.data.proxy.WebSocket': 'bower_components/ext.ux.data.proxy.websocket/WebSocket.js' ,
43 | // Require the Ext.ux.WebSocket dependency
44 | 'Ext.ux.WebSocket': 'bower_components/ext.ux.websocket/WebSocket.js'
45 | }
46 | });
47 |
48 | Ext.require (['Ext.ux.data.proxy.WebSocket']);
49 | ```
50 |
51 | ## Usage
52 | Load `Ext.ux.data.proxy.WebSocket` via `Ext.require`:
53 |
54 | ```javascript
55 | Ext.Loader.setConfig ({
56 | enabled: true
57 | });
58 |
59 | Ext.require (['Ext.ux.data.proxy.WebSocket']);
60 | ```
61 |
62 | Now, you are ready to use it in your code!
63 |
64 | First define a new `Ext.data.Model`:
65 |
66 | ```javascript
67 | Ext.define ('myModel', {
68 | extend: 'Ext.data.Model' ,
69 | fields: ['id', 'name', 'age'] ,
70 | // Ext.ux.data.proxy.WebSocket can be put here in the model or in the store
71 | proxy: {
72 | type: 'websocket' ,
73 | storeId: 'myStore',
74 | url: 'ws://localhost:8888' ,
75 | reader: {
76 | type: 'json' ,
77 | root: 'user'
78 | }
79 | }
80 | });
81 | ```
82 |
83 | Second create a `Ext.data.Store`:
84 |
85 | ```javascript
86 | var store = Ext.create ('Ext.data.Store', {
87 | model: 'myModel',
88 | storeId: 'myStore'
89 | });
90 | ```
91 |
92 | Third attach the store to a grid or a chart:
93 |
94 | ```javascript
95 | var myGrid = Ext.create ('Ext.grid.Panel', {
96 | title: 'My Grid' ,
97 | store: store ,
98 | ...
99 | });
100 |
101 | var myGrid = Ext.create ('Ext.chart.Chart', {
102 | title: 'My Chart' ,
103 | store: store ,
104 | ...
105 | });
106 | ```
107 |
108 | In the above example, a WebSocket proxy is defined into the model (the same thing can be done into stores): when a CRUD operation is made by its store (through sync/load methods), a 'create'/'read'/'update'/'destroy' event is sent to the server.
109 | At this point, the server intercepts the event, parses the request, and then replies back with the same event.
110 | If you want/need to specify your communication protocol (you wanna CRUD operations like 'createUsers','readUsers','updateUsers','destroyUsers'), just use the api configuration:
111 |
112 | ```javascript
113 | proxy: {
114 | type: 'websocket' ,
115 | storeId: 'myStore',
116 | url: 'ws://localhost:8888' ,
117 | api: {
118 | create: 'createUsers' ,
119 | read: 'readUsers' ,
120 | update: 'updateUsers' ,
121 | destroy: 'destroyUsers'
122 | } ,
123 | reader: {
124 | type: 'json' ,
125 | root: 'user'
126 | }
127 | }
128 | ```
129 |
130 | With this configuration, each sync/load operation made by the store will fire the right CRUD-overridden action.
131 |
132 | Now, you're ready to watch the magic in action!
133 |
134 | ## Run the demo
135 | The demo has a back-end written in [**NodeJS**](http://nodejs.org/) so you have to install it first.
136 | Now, clone the repo locally:
137 |
138 | ```bash
139 | $ git clone https://github.com/wilk/Ext.ux.data.proxy.WebSocket
140 | $ cd Ext.ux.data.proxy.WebSocket
141 | ```
142 |
143 | Then use [**NPM**](https://www.npmjs.org/) and [**Bower**](http://bower.io/) to satisfy every dependencies:
144 |
145 | ```bash
146 | $ npm install && bower install
147 | ```
148 |
149 | Last step, launch the server:
150 |
151 | ```bash
152 | $ node demo/server
153 | ```
154 |
155 | Now, you have a websocket listening at port 9001 on the server side!
156 | Then, type in the address bar of your browser: **http://localhost/Ext.ux.data.proxy.WebSocket/demo** and play the demo ;)
157 |
158 | ## Documentation
159 | You can build the documentation (like ExtJS/Sencha Touch Docs) with [**jsduck**](https://github.com/senchalabs/jsduck):
160 |
161 | ```bash
162 | $ jsduck ux --output /var/www/docs
163 | ```
164 |
165 | It will make the documentation into docs dir and it will be visible at: http://localhost/docs
166 |
167 | ## License
168 | The MIT License (MIT)
169 |
170 | Copyright (c) 2013 Vincenzo Ferrari
171 |
172 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
173 |
174 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
175 |
176 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
177 |
--------------------------------------------------------------------------------
/WebSocket.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @class Ext.ux.data.proxy.WebSocket
3 | * @author Vincenzo Ferrari
4 | *
5 | * HTML5 WebSocket proxy
6 | *
7 | * How it works?
8 | * Ext.ux.data.proxy.WebSocket provides an interface between stores and readers/writers.
9 | * By default, this proxy communicates with the server through CRUD operations: each operation is identified by its name, as create, read, update and destroy (instead of delete).
10 | * Let's have a look to the first example:
11 | *
12 | * Ext.define ('model', {
13 | * extend: 'Ext.data.Model' ,
14 | * fields: ['id', 'name', 'age'] ,
15 | * proxy: {
16 | * type: 'websocket' ,
17 | * storeId: 'myStore',
18 | * url: 'ws://localhost:8888' ,
19 | * reader: {
20 | * type: 'json' ,
21 | * root: 'user'
22 | * }
23 | * }
24 | * });
25 | *
26 | * var store = Ext.create ('Ext.data.Store', {
27 | * model: 'model',
28 | * storeId: 'myStore'
29 | * });
30 | *
31 | * In the above example, a WebSocket proxy is defined into the model (the same thing can be done into stores): when a CRUD operation is made by its store (through sync/load methods), a 'create'/'read'/'update'/'destroy' event is sent to the server.
32 | * At this point, the server intercepts the event, parses the request, and then replies back with the same event.
33 | * If you want/need to specify your communication protocol (you wanna CRUD operations like 'createUsers','readUsers','updateUsers','destroyUsers'), just use the api configuration:
34 | *
35 | * proxy: {
36 | * type: 'websocket' ,
37 | * storeId: 'myStore',
38 | * url: 'ws://localhost:8888' ,
39 | * api: {
40 | * create: 'createUsers' ,
41 | * read: 'readUsers' ,
42 | * update: 'updateUsers' ,
43 | * destroy: 'destroyUsers'
44 | * } ,
45 | * reader: {
46 | * type: 'json' ,
47 | * root: 'user'
48 | * }
49 | * }
50 | *
51 | * With this configuration, each sync/load operation made by the store will fire the right CRUD-overridden action.
52 | *
53 | * Reached this point, you can easily attach your store to grids and charts, and watch the WebSocket magic in action!
54 | */
55 | Ext.define('Ext.ux.data.proxy.WebSocket', {
56 | extend: 'Ext.data.proxy.Proxy',
57 | alias: 'proxy.websocket',
58 |
59 | requires: ['Ext.ux.WebSocket'],
60 |
61 | /**
62 | * @property {Object} callbacks
63 | * @private
64 | * Callbacks stack
65 | */
66 | callbacks: {},
67 |
68 | config: {
69 | /**
70 | * @cfg {String} storeId (required) Id of the store associated
71 | */
72 | storeId: '',
73 |
74 | /**
75 | * @cfg {Object} api CRUD operation for the communication with the server
76 | */
77 | api: {
78 | create: 'create',
79 | read: 'read',
80 | update: 'update',
81 | destroy: 'destroy'
82 | },
83 |
84 | /**
85 | * @cfg {String} url (required) The URL to connect the websocket
86 | */
87 | url: '',
88 |
89 | /**
90 | * @cfg {String} [pageParam="page"]
91 | * The name of the 'page' parameter to send in a request. Defaults to 'page'. Set this to `''` if you don't
92 | * want to send a page parameter.
93 | */
94 | pageParam: 'page',
95 |
96 | /**
97 | * @cfg {String} [startParam="start"]
98 | * The name of the 'start' parameter to send in a request. Defaults to 'start'. Set this to `''` if you don't
99 | * want to send a start parameter.
100 | */
101 | startParam: 'start',
102 |
103 | /**
104 | * @cfg {String} [limitParam="limit"]
105 | * The name of the 'limit' parameter to send in a request. Defaults to 'limit'. Set this to `''` if you don't
106 | * want to send a limit parameter.
107 | */
108 | limitParam: 'limit',
109 |
110 | /**
111 | * @cfg {String} [groupParam="group"]
112 | * The name of the 'group' parameter to send in a request. Defaults to 'group'. Set this to `''` if you don't
113 | * want to send a group parameter.
114 | */
115 | groupParam: 'group',
116 |
117 | /**
118 | * @cfg {String} [groupDirectionParam="groupDir"]
119 | * The name of the direction parameter to send in a request. **This is only used when simpleGroupMode is set to
120 | * true.**
121 | */
122 | groupDirectionParam: 'groupDir',
123 |
124 | /**
125 | * @cfg {String} [sortParam="sort"]
126 | * The name of the 'sort' parameter to send in a request. Defaults to 'sort'. Set this to `''` if you don't
127 | * want to send a sort parameter.
128 | */
129 | sortParam: 'sort',
130 |
131 | /**
132 | * @cfg {String} [filterParam="filter"]
133 | * The name of the 'filter' parameter to send in a request. Defaults to 'filter'. Set this to `''` if you don't
134 | * want to send a filter parameter.
135 | */
136 | filterParam: 'filter',
137 |
138 | /**
139 | * @cfg {String} [directionParam="dir"]
140 | * The name of the direction parameter to send in a request. **This is only used when simpleSortMode is set to
141 | * true.**
142 | */
143 | directionParam: 'dir',
144 |
145 | /**
146 | * @cfg {Boolean} [simpleSortMode=false]
147 | * Enabling simpleSortMode in conjunction with remoteSort will only send one sort property and a direction when a
148 | * remote sort is requested. The {@link #directionParam} and {@link #sortParam} will be sent with the property name
149 | * and either 'ASC' or 'DESC'.
150 | */
151 | simpleSortMode: false,
152 |
153 | /**
154 | * @cfg {Boolean} [simpleGroupMode=false]
155 | * Enabling simpleGroupMode in conjunction with remoteGroup will only send one group property and a direction when a
156 | * remote group is requested. The {@link #groupDirectionParam} and {@link #groupParam} will be sent with the property name and either 'ASC'
157 | * or 'DESC'.
158 | */
159 | simpleGroupMode: false,
160 |
161 | /**
162 | * @cfg {Object} extraParams
163 | * Extra parameters that will be included on every request. Individual requests with params of the same name
164 | * will override these params when they are in conflict.
165 | */
166 | extraParams: {},
167 |
168 | /**
169 | * @cfg {String} protocol The protocol to use in the connection
170 | */
171 | protocol: null,
172 |
173 | /**
174 | * @cfg {Ext.ux.WebSocket} websocket An instance of Ext.ux.WebSocket (no needs to make a new one)
175 | */
176 | websocket: null,
177 |
178 | /**
179 | * @cfg {Boolean} autoReconnect If the connection is closed by the server, it tries to re-connect again. The execution interval time of this operation is specified in autoReconnectInterval
180 | */
181 | autoReconnect: true,
182 |
183 | /**
184 | * @cfg {Int} autoReconnectInterval Execution time slice of the autoReconnect operation, specified in milliseconds.
185 | */
186 | autoReconnectInterval: 5000,
187 |
188 | /**
189 | * @cfg {Boolean} keepUnsentMessages Keep unsent messages and try to send them back after the connection is open again.
190 | */
191 | keepUnsentMessages: true
192 | },
193 |
194 | /**
195 | * Creates new Ext.ux.data.proxy.WebSocket
196 | * @param {String/Object} config To instatiate this proxy, just define it on a model or a store.
197 | *
198 | * // *** On a Model ***
199 | * Ext.define ('model', {
200 | * extend: 'Ext.data.Model' ,
201 | * fields: ['id', 'name', 'age'] ,
202 | * proxy: {
203 | * type: 'websocket' ,
204 | * storeId: 'myStore',
205 | * url: 'ws://localhost:8888' ,
206 | * reader: {
207 | * type: 'json' ,
208 | * root: 'user'
209 | * }
210 | * }
211 | * });
212 | *
213 | * var store = Ext.create ('Ext.data.Store', {
214 | * model: 'model',
215 | * storeId: 'myStore'
216 | * });
217 | *
218 | * // *** Or on a store ***
219 | * Ext.define ('model', {
220 | * extend: 'Ext.data.Model' ,
221 | * fields: ['id', 'name', 'age']
222 | * });
223 | *
224 | * var store = Ext.create ('Ext.data.Store', {
225 | * model: 'model',
226 | * storeId: 'myStore' ,
227 | * proxy: {
228 | * type: 'websocket' ,
229 | * storeId: 'myStore',
230 | * url: 'ws://localhost:8888' ,
231 | * reader: {
232 | * type: 'json' ,
233 | * root: 'user'
234 | * }
235 | * }
236 | * });
237 | *
238 | * In each case, a storeId has to be specified and of course a url for the websocket.
239 | * If you already have an instance of Ext.ux.WebSocket, just use it in place of url:
240 | *
241 | * var ws = Ext.create ('Ext.ux.WebSocket', 'ws://localhost:8888');
242 | *
243 | * var store = Ext.create ('Ext.data.Store', {
244 | * model: 'model',
245 | * storeId: 'myStore' ,
246 | * proxy: {
247 | * type: 'websocket' ,
248 | * storeId: 'myStore',
249 | * websocket: ws ,
250 | * reader: {
251 | * type: 'json' ,
252 | * root: 'user'
253 | * }
254 | * }
255 | * });
256 | *
257 | * @return {Ext.ux.WebSocket} An instance of Ext.ux.WebSocket or null if an error occurred.
258 | */
259 | constructor: function (cfg) {
260 | var me = this;
261 |
262 | // Requires a configuration
263 | if (Ext.isEmpty(cfg)) {
264 | Ext.Error.raise('A configuration is needed!');
265 | return false;
266 | }
267 |
268 | me.initConfig(cfg);
269 | me.mixins.observable.constructor.call(me, cfg);
270 |
271 | // Requires a storeId
272 | if (Ext.isEmpty(me.getStoreId())) {
273 | Ext.Error.raise('The storeId field is needed!');
274 | return false;
275 | }
276 |
277 | //if (Ext.isEmpty (cfg.websocket)) {
278 | if (Ext.isEmpty(me.getWebsocket())) {
279 | me.setWebsocket(Ext.create('Ext.ux.WebSocket', {
280 | url: me.getUrl(),
281 | protocol: me.getProtocol(),
282 | communicationType: 'event',
283 | autoReconnect: me.getAutoReconnect(),
284 | autoReconnectInterval: me.getAutoReconnectInterval(),
285 | keepUnsentMessages: me.getKeepUnsentMessages()
286 | }));
287 | }
288 |
289 | var ws = me.getWebsocket();
290 |
291 | // Forces the event communication
292 | if (ws.getCommunicationType() !== 'event') {
293 | Ext.Error.raise('Ext.ux.WebSocket must use event communication type (set communicationType to event)!');
294 | return false;
295 | }
296 |
297 | ws.on(me.getApi().create, function (ws, data) {
298 | me.completeTask('create', me.getApi().create, data);
299 | });
300 |
301 | ws.on(me.getApi().read, function (ws, data) {
302 | me.completeTask('read', me.getApi().read, data);
303 | });
304 |
305 | ws.on(me.getApi().update, function (ws, data) {
306 | me.completeTask('update', me.getApi().update, data);
307 | });
308 |
309 | ws.on(me.getApi().destroy, function (ws, data) {
310 | me.completeTask('destroy', me.getApi().destroy, data);
311 | });
312 |
313 | // Allows to define WebSocket proxy both into a model and a store
314 | me.callParent([cfg]);
315 |
316 | return me;
317 | },
318 |
319 | /**
320 | * Encodes the array of {@link Ext.util.Sorter} objects into a string to be sent in the request url. By default,
321 | * this simply JSON-encodes the sorter data
322 | * @param {Ext.util.Sorter[]} sorters The array of {@link Ext.util.Sorter Sorter} objects
323 | * @param {Boolean} [preventArray=false] Prevents the items from being output as an array.
324 | * @return {String} The encoded sorters
325 | */
326 | encodeSorters: function (sorters, preventArray) {
327 | var out = [],
328 | length = sorters.length,
329 | i;
330 |
331 | for (i = 0; i < length; i++) {
332 | out[i] = sorters[i].serialize();
333 | }
334 |
335 | return Ext.encode(preventArray ? out[0] : out);
336 | },
337 |
338 | /**
339 | * Encodes the array of {@link Ext.util.Filter} objects into a string to be sent in the request url. By default,
340 | * this simply JSON-encodes the filter data
341 | * @param {Ext.util.Filter[]} filters The array of {@link Ext.util.Filter Filter} objects
342 | * @return {String} The encoded filters
343 | */
344 | encodeFilters: function (filters) {
345 | var out = [],
346 | length = filters.length,
347 | i, op;
348 |
349 | for (i = 0; i < length; i++) {
350 | out[i] = filters[i].serialize();
351 | }
352 |
353 | return Ext.encode(out);
354 | },
355 |
356 | /**
357 | * @private
358 | * Copy any sorters, filters etc into the params so they can be sent over the wire
359 | */
360 | getParams: function (operation) {
361 | var me = this,
362 | params = {},
363 | grouper = operation.getGrouper(),
364 | sorters = operation.getSorters(),
365 | filters = operation.getFilters(),
366 | page = operation.getPage(),
367 | start = operation.getStart(),
368 | limit = operation.getLimit(),
369 | simpleSortMode = me.getSimpleSortMode(),
370 | simpleGroupMode = me.getSimpleGroupMode(),
371 | pageParam = me.getPageParam(),
372 | startParam = me.getStartParam(),
373 | limitParam = me.getLimitParam(),
374 | groupParam = me.getGroupParam(),
375 | groupDirectionParam = me.getGroupDirectionParam(),
376 | sortParam = me.getSortParam(),
377 | filterParam = me.getFilterParam(),
378 | directionParam = me.getDirectionParam(),
379 | hasGroups, index;
380 |
381 | if (pageParam && page) {
382 | params[pageParam] = page;
383 | }
384 |
385 | if (startParam && (start || start === 0)) {
386 | params[startParam] = start;
387 | }
388 |
389 | if (limitParam && limit) {
390 | params[limitParam] = limit;
391 | }
392 |
393 | hasGroups = groupParam && grouper;
394 | if (hasGroups) {
395 | // Grouper is a subclass of sorter, so we can just use the sorter method
396 | if (simpleGroupMode) {
397 | params[groupParam] = grouper.getProperty();
398 | params[groupDirectionParam] = grouper.getDirection();
399 | } else {
400 | params[groupParam] = me.encodeSorters([grouper], true);
401 | }
402 | }
403 |
404 | if (sortParam && sorters && sorters.length > 0) {
405 | if (simpleSortMode) {
406 | index = 0;
407 | // Group will be included in sorters, so grab the next one
408 | if (sorters.length > 1 && hasGroups) {
409 | index = 1;
410 | }
411 | params[sortParam] = sorters[index].getProperty();
412 | params[directionParam] = sorters[index].getDirection();
413 | } else {
414 | params[sortParam] = me.encodeSorters(sorters);
415 | }
416 |
417 | }
418 |
419 | if (filterParam && filters && filters.length > 0) {
420 | params[filterParam] = me.encodeFilters(filters);
421 | }
422 |
423 | return params;
424 | },
425 |
426 | /**
427 | * @method create
428 | * Starts a new CREATE operation (pull)
429 | * The use of this method is discouraged: it's invoked by the store with sync/load operations.
430 | * Use api config instead
431 | */
432 | create: function (operation) {
433 | this.runTask(this.getApi().create, operation);
434 | },
435 |
436 | /**
437 | * @method read
438 | * Starts a new READ operation (pull)
439 | * The use of this method is discouraged: it's invoked by the store with sync/load operations.
440 | * Use api config instead
441 | */
442 | read: function (operation) {
443 | this.runTask(this.getApi().read, operation);
444 | },
445 |
446 | /**
447 | * @method update
448 | * Starts a new CREATE operation (pull)
449 | * The use of this method is discouraged: it's invoked by the store with sync/load operations.
450 | * Use api config instead
451 | */
452 | update: function (operation) {
453 | this.runTask(this.getApi().update, operation);
454 | },
455 |
456 | /**
457 | * @method erase
458 | * Starts a new DESTROY operation (pull)
459 | * The use of this method is discouraged: it's invoked by the store with sync/load operations.
460 | * Use api config instead
461 | */
462 | erase: function (operation) {
463 | this.runTask(this.getApi().destroy, operation);
464 | },
465 |
466 | /**
467 | * @method runTask
468 | * Starts a new operation (pull)
469 | * @private
470 | */
471 | runTask: function (action, operation) {
472 | var me = this ,
473 | data = {} ,
474 | ws = me.getWebsocket() ,
475 | i = 0;
476 |
477 | // Callbacks store
478 | me.callbacks[action] = {
479 | operation: operation
480 | };
481 |
482 | // Treats 'read' as a string event, with no data inside
483 | if (action === me.getApi().read) {
484 | var initialParams = Ext.apply({}, operation.getParams());
485 |
486 | data = Ext.applyIf(initialParams, me.getExtraParams() || {});
487 |
488 | // copy any sorters, filters etc into the params so they can be sent over the wire
489 | Ext.applyIf(data, me.getParams(operation));
490 | }
491 | // Create, Update, Destroy
492 | else {
493 | var writer = Ext.StoreManager.lookup(me.getStoreId()).getProxy().getWriter(),
494 | records = operation.getRecords();
495 |
496 | data = [];
497 |
498 | for (i = 0; i < records.length; i++) {
499 | data.push(writer.getRecordData(records[i]));
500 | }
501 | }
502 |
503 | ws.send(action, data);
504 | },
505 |
506 | /**
507 | * @method completeTask
508 | * Completes a pending operation (push/pull)
509 | * @private
510 | */
511 | completeTask: function (action, event, data) {
512 | var me = this ,
513 | resultSet = me.getReader().read(data);
514 |
515 | // Server push case: the store is get up-to-date with the incoming data
516 | if (!me.callbacks[event]) {
517 | var store = Ext.StoreManager.lookup(me.getStoreId());
518 |
519 | if (typeof store === 'undefined') {
520 | Ext.Error.raise('Unrecognized store: check if the storeId passed into configuration is right.');
521 | return false;
522 | }
523 |
524 | if (action === 'update') {
525 | for (var i = 0; i < resultSet.records.length; i++) {
526 | var record = store.getById(resultSet.records[i].getId());
527 |
528 | if (record) {
529 | record.set(resultSet.records[i].data);
530 | }
531 | }
532 |
533 | store.commitChanges();
534 | }
535 | else if (action === 'destroy') {
536 | Ext.each(resultSet.records, function (record) {
537 | store.remove(record);
538 | });
539 |
540 | store.commitChanges();
541 | }
542 | else {
543 | store.loadData(resultSet.records, true);
544 | store.fireEvent('load', store);
545 | }
546 | }
547 | // Client request case: a callback function (operation) has to be called
548 | else {
549 | var opt = me.callbacks[event].operation ,
550 | records = opt.records || data;
551 |
552 | delete me.callbacks[event];
553 |
554 | if (typeof opt.setResultSet === 'function') opt.setResultSet(resultSet);
555 | else opt.resultSet = resultSet;
556 |
557 | opt.setSuccessful(true);
558 | }
559 | }
560 | });
561 |
--------------------------------------------------------------------------------