Many classes have shortcut names used when creating (instantiating) a class with a
configuration object. The shortcut name is referred to as an alias
(or xtype
if the
class extends Ext.Component). The alias/xtype is listed next to the class name of
applicable classes for quick reference.
Framework classes or their members may be specified as private
or protected
. Else,
the class / member is public
. Public
, protected
, and private
are access
descriptors used to convey how and when the class or class member should be used.
Public classes and class members are available for use by any other class or application code and may be relied upon as a stable and persistent within major product versions. Public classes and members may safely be extended via a subclass.
Protected class members are stable public
members intended to be used by the
owning class or its subclasses. Protected members may safely be extended via a subclass.
Private classes and class members are used internally by the framework and are not intended to be used by application developers. Private classes and members may change or be omitted from the framework at any time without notice and should not be relied upon in application logic.
static
label next to the
method name. *See Static below.Below is an example class member that we can disect to show the syntax of a class member (the lookupComponent method as viewed from the Ext.button.Button class in this case).
Let's look at each part of the member row:
lookupComponent
in this example)( item )
in this example)Ext.Component
in this case). This may be omitted for methods that do not
return anything other than undefined
or may display as multiple possible values
separated by a forward slash /
signifying that what is returned may depend on the
results of the method call (i.e. a method may return a Component if a get method calls is
successful or false
if unsuccessful which would be displayed as
Ext.Component/Boolean
).PROTECTED
in
this example - see the Flags section below)Ext.container.Container
in this example). The source
class will be displayed as a blue link if the member originates from the current class
and gray if it is inherited from an ancestor or mixed-in class.view source
in the example)item : Object
in the example).undefined
a "Returns" section
will note the type of class or object returned and a description (Ext.Component
in the
example)Available since 3.4.0
- not pictured in
the example) just after the member descriptionDefaults to: false
)The API documentation uses a number of flags to further commnicate the class member's function and intent. The label may be represented by a text label, an abbreviation, or an icon.
classInstance.method1().method2().etc();
false
is returned from
an event handler- Indicates a framework class
- A singleton framework class. *See the singleton flag for more information
- A component-type framework class (any class within the Ext JS framework that extends Ext.Component)
- Indicates that the class, member, or guide is new in the currently viewed version
- Indicates a class member of type config
- Indicates a class member of type property
- Indicates a class member of type
method
- Indicates a class member of type event
- Indicates a class member of type
theme variable
- Indicates a class member of type
theme mixin
- Indicates that the class, member, or guide is new in the currently viewed version
Just below the class name on an API doc page is a row of buttons corresponding to the types of members owned by the current class. Each button shows a count of members by type (this count is updated as filters are applied). Clicking the button will navigate you to that member section. Hovering over the member-type button will reveal a popup menu of all members of that type for quick navigation.
Getting and setter methods that correlate to a class config option will show up in the methods section as well as in the configs section of both the API doc and the member-type menus just beneath the config they work with. The getter and setter method documentation will be found in the config row for easy reference.
Your page history is kept in localstorage and displayed (using the available real estate) just below the top title bar. By default, the only search results shown are the pages matching the product / version you're currently viewing. You can expand what is displayed by clicking on the button on the right-hand side of the history bar and choosing the "All" radio option. This will show all recent pages in the history bar for all products / versions.
Within the history config menu you will also see a listing of your recent page visits. The results are filtered by the "Current Product / Version" and "All" radio options. Clicking on the button will clear the history bar as well as the history kept in local storage.
If "All" is selected in the history config menu the checkbox option for "Show product details in the history bar" will be enabled. When checked, the product/version for each historic page will show alongside the page name in the history bar. Hovering the cursor over the page names in the history bar will also show the product/version as a tooltip.
Both API docs and guides can be searched for using the search field at the top of the page.
On API doc pages there is also a filter input field that filters the member rows using the filter string. In addition to filtering by string you can filter the class members by access level, inheritance, and read only. This is done using the checkboxes at the top of the page.
The checkbox at the bottom of the API class navigation tree filters the class list to include or exclude private classes.
Clicking on an empty search field will show your last 10 searches for quick navigation.
Each API doc page (with the exception of Javascript primitives pages) has a menu view of metadata relating to that class. This metadata view will have one or more of the following:
Ext.button.Button
class has an alternate class name of Ext.Button
). Alternate class
names are commonly maintained for backward compatibility.Runnable examples (Fiddles) are expanded on a page by default. You can collapse and expand example code blocks individually using the arrow on the top-left of the code block. You can also toggle the collapse state of all examples using the toggle button on the top-right of the page. The toggle-all state will be remembered between page loads.
Class members are collapsed on a page by default. You can expand and collapse members using the arrow icon on the left of the member row or globally using the expand / collapse all toggle button top-right.
Viewing the docs on narrower screens or browsers will result in a view optimized for a smaller form factor. The primary differences between the desktop and "mobile" view are:
The class source can be viewed by clicking on the class name at the top of an API doc page. The source for class members can be viewed by clicking on the "view source" link on the right-hand side of the member row.
Most web applications require the use of a client-side and a server-side. The client-side code cannot directly call server-side functions. Instead, the client sends requests, the server handles the requests, and then returns information to the client. Ext Direct allows developers to expose a list of server-side classes that can then be called directly from the client-side code, making the process of building applications much simpler. This allows you to streamline communication between client-side and server-side, resulting in less code, naming parity throughout your environment, and smarter XHR handling. Other benefits include:
To put this into practice, let's say you have a server-side class named Dog
with a
method named bark
. When using Ext Direct, you can call Dog.bark()
from within your
JavaScript code.
To do this, you simply need to provide Ext Direct with a list of your server-side classes and methods and Ext Direct will then act as a proxy, giving you front-end access to your server-side environment.
Note: There are many variations in server side technology, but this guide uses the Remoting Provider along with PHP and MySQL.
To begin, let's generate an application using Sencha Cmd. Simply open your terminal, and issue the following command:
sencha -sdk path/to/ext/ generate app -classic DirectApp ./DirectApp
You should now have a fully functional Classic application. We'll work with the pre-configured views in this starter app to demonstrate connecting with Ext Direct.
Note: Your application should be available at http://localhost/DirectApp or http://localhost:1841/ if you're using "sencha app watch".
Our starter app already has a grid displaying names, emails, and
phone numbers. However, it is using local data by way of a
memory proxy. Let's begin by opening the "app/store/Personnel.js"
file. Once opened, remove the data object and change the proxy type to 'direct', and add
a directFn
of "QueryDatabase.getResults". This is the function that we will create
using PHP. The resulting code should look like this:
Ext.define('DirectApp.store.Personnel', {
extend: 'Ext.data.Store',
alias: 'store.personnel',
fields: [
'name', 'email', 'phone'
],
proxy: {
type: 'direct',
directFn: "QueryDatabase.getResults"
},
autoLoad: true
});
Refreshing your app should now result in an empty grid since we have not yet provided any data via our direct proxy.
Let's replace the data with something that already fits the name/email/phone fields. Use this SQL to create a "heroes" table:
DROP TABLE IF EXISTS `heroes`;
CREATE TABLE `heroes` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(70) DEFAULT NULL,
`email` varchar(255) DEFAULT NULL,
`phone` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
LOCK TABLES `heroes` WRITE;
/*!40000 ALTER TABLE `heroes` DISABLE KEYS */;
INSERT INTO `heroes` (`id`, `name`, `email`, `phone`)
VALUES
(1,'Thanos','[email protected]','5555555555'),
(2,'Spider Man','[email protected]','2125555555'),
(3,'Daredevil','[email protected]','2125555555'),
(4,'The Maker','[email protected]','2125555555'),
(5,'Rocket','[email protected]','5555555555'),
(6,'Galactus','[email protected]','5555555555'),
(7,'Silver Surfer','[email protected]','5555555555'),
(8,'Hulk','[email protected]','2125555555'),
(9,'Squirrel Girl','[email protected]','2125555555'),
(10,'Thor','[email protected]','5555555555');
/*!40000 ALTER TABLE `heroes` ENABLE KEYS */;
UNLOCK TABLES;
You should now have a MySQL table populated with 10 records that we'll display in our grid. Now that we have data, let's create a connection.
In the root directory of our app, create a folder called 'php' followed by another one inside it called "classes". Within "classes" create a file called "QueryDatabase.php".
We'll be utilizing PHP's MySQLi extension which works with MySQL 4.1.3 and above (any version released after mid-2004 will be fine).
We won't delve too far into the PHP code. Most of it should be pretty straight forward for anyone who has queried MySQL via PHP. We're defining a new class, declaring some variables, creating a connector, and making a function that gets results from the database.
<?php
class QueryDatabase {
private $_db;
protected $_result;
public $results;
public function __construct() {
$this->_db = new mysqli('host', 'username' ,'password', 'database');
$_db = $this->_db;
if ($_db->connect_error) {
die('Connection Error: ' . $_db->connect_error);
}
return $_db;
}
public function getResults($params) {
$_db = $this->_db;
$_result = $_db->query("SELECT name,email,phone FROM heroes") or
die('Connection Error: ' . $_db->connect_error);
$results = array();
while ($row = $_result->fetch_assoc()) {
array_push($results, $row);
}
$this->_db->close();
return $results;
}
}
To recap, we declared some variables at the top of the class and and made two functions that will help us as we expand our application.
The first function (__construct) creates the database connection instance. If it fails to connect, it will provide a detailed error message.
The second function (getResults) uses the first function to open a connection and queries
the database for all of the column fields. We then push all of the results into an array
called $results
by way of a while statement. Finally, we close the connection to the
database and return the results.
Note: Replace hostname
, password
, and database
with your own credentials.
Let's go up a level to the "php" directory and create a new file called "config.php" and add the following code:
<?php
function get_extdirect_api() {
$API = array(
'QueryDatabase' => array(
'methods' => array(
'getResults' => array(
'len' => 1
)
)
)
);
return $API;
}
This exposes the functions we want to be made available to our Ext application to call the server. For now, we only need to add the 'getResults' method we created above.
That's all there is to our config.php file for now.
Next, we'll need a router to make sure the correct methods are called. The router is where
the calls from Ext Direct
get routed to the correct class using a Remote Procedure
Call (RPC).
While still in the "php" directory, let's create another file called "router.php" and add the following code.
<?php
require('config.php');
class BogusAction {
public $action;
public $method;
public $data;
public $tid;
}
$isForm = false;
$isUpload = false;
if (isset($HTTP_RAW_POST_DATA)) {
header('Content-Type: text/javascript');
$data = json_decode($HTTP_RAW_POST_DATA);
}
else if(isset($_POST['extAction'])){ // form post
$isForm = true;
$isUpload = $_POST['extUpload'] == 'true';
$data = new BogusAction();
$data->action = $_POST['extAction'];
$data->method = $_POST['extMethod'];
$data->tid = isset($_POST['extTID']) ? $_POST['extTID'] : null;
$data->data = array($_POST, $_FILES);
}
else {
die('Invalid request.');
}
function doRpc($cdata){
$API = get_extdirect_api('router');
try {
if (!isset($API[$cdata->action])) {
throw new Exception('Call to undefined action: ' . $cdata->action);
}
$action = $cdata->action;
$a = $API[$action];
$method = $cdata->method;
$mdef = $a['methods'][$method];
if (!$mdef){
throw new Exception("Call to undefined method: $method " .
"in action $action");
}
$r = array(
'type'=>'rpc',
'tid'=>$cdata->tid,
'action'=>$action,
'method'=>$method
);
require_once("classes/$action.php");
$o = new $action();
if (isset($mdef['len'])) {
$params = isset($cdata->data) && is_array($cdata->data) ? $cdata->data : array();
}
else {
$params = array($cdata->data);
}
array_push($params, $cdata->metadata);
$r['result'] = call_user_func_array(array($o, $method), $params);
}
catch(Exception $e){
$r['type'] = 'exception';
$r['message'] = $e->getMessage();
$r['where'] = $e->getTraceAsString();
}
return $r;
}
$response = null;
if (is_array($data)) {
$response = array();
foreach($data as $d){
$response[] = doRpc($d);
}
}
else{
$response = doRpc($data);
}
if ($isForm && $isUpload){
echo '<html><body><textarea>';
echo json_encode($response);
echo '</textarea></body></html>';
}
else{
echo json_encode($response);
}
This code will require the config file containing the methods we defined for API
exposure. We also add a doRpc
function that will provide important information about
our data and responses from the server.
Note: Slightly more advanced version of router.php (and api.php in the next section) can be found within the "ext/examples/kitchensink/data/direct" folder within the SDK.
Finally, let's create a file called 'api.php' and populate it with the following code:
<?php
require('config.php');
header('Content-Type: text/javascript');
// convert API config to Ext Direct spec
$API = get_extdirect_api();
$actions = array();
foreach ($API as $aname=>&$a) {
$methods = array();
foreach ($a['methods'] as $mname=>&$m) {
if (isset($m['len'])) {
$md = array(
'name'=>$mname,
'len'=>$m['len']
);
} else {
$md = array(
'name'=>$mname,
'params'=>$m['params']
);
}
if (isset($m['formHandler']) && $m['formHandler']) {
$md['formHandler'] = true;
}
$methods[] = $md;
}
$actions[$aname] = $methods;
}
$cfg = array(
'url'=>'php/router.php',
'type'=>'remoting',
'actions'=>$actions
);
echo 'var Ext = Ext || {}; Ext.REMOTING_API = ';
echo json_encode($cfg);
echo ';';
This file uses the "config.php" file we made earlier and sets the output header to JavaScript. This ensures that the browser will interpret any output as JavaScript. It then proceeds to turn our config and router PHP files into JSON so the right method is called when Ext Direct calls it.
Again, the content of "api.php" can be found within the "ext/examples/kitchensink/data/direct" folder within the SDK.
Next, let's tell Cmd about "api.php", the application's "entry point" to our Direct. The best way to communicate our needs to Cmd is by way of "app.json's" javascript array. Open "app.json" and find the JS array. Then add "api.php" as a remote inclusion. The resulting array should look like this:
"js": [
{
"path": "php/api.php",
"remote": true
},
{
"path": "app.js",
"bundle": true
}
],
If you are not using Cmd to build your application, you can add "api.php" to a script tag in your application's "index.html" file. Just make sure that "api.php" line comes before the "app.js" line.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>App Title</title>
<!--Ext JS-->
<link rel="stylesheet" type="text/css" href="resources/css/ext-all.css">
<script src="extjs/ext-all-debug.js"></script>
<!--Application JS→
<script src="php/api.php"></script>
<script src="app.js"></script>
</head>
<body>
</body>
</html>
Because we're using the HTML5 document type, we're allowed to omit the type in a script tag,
it assumes that all <script>
tags will be JavaScript which helps cut down our bytes.
We've made it to our final step to populate the grid with results! We now need to add a provider to the direct manager. As we discussed earlier, there are two providers in the framework, but we’ll be using the remoting api for this particular project. Open your "Application.js" file and add the provider to the direct manager within the launch function. It should like this:
launch: function () {
Ext.direct.Manager.addProvider(Ext.REMOTING_API);
},
Note: "Ext.REMOTING_API" is the name of the variable that was created by the JavaScript code printed in "api.php". You can use any variable name you like but it should be the same in both places.
Refreshing your application should now display our new grid results. As you can see, there's a little bit of setup involved, but once complete, adding new methods is simply a matter of writing them and adding them to your config file. You then have direct access to your server side methods, which streamlines your code and a whole lot more!