Académique Documents
Professionnel Documents
Culture Documents
Ext Core is a lightweight and feature rich core JavaScript library available
under an MIT license. Ext Core is packed full of exciting features intended to
allow for rapid web development while encouraging well designed and
scalable code. This library provides abstractions for DOM
manipulation/traversal, Ajax, Events and custom events, animations,
templating, OO mechanisms and more. Ext Core is released under an MIT
license and is perfect for inclusion in a dynamic webpage or even a small
application.
Download
Ext Core can be downloaded here and the latest information can be found on
the Ext Core Project Page.
Ext Core ships with both a debug version as well as a production version.
The production version has been minified (whitespace, carriage returns and
comments removed) and obfuscated (all local variables have been renamed
to shorter versions) using YUI Compressor. You should always use the -
debug version when developing since you'll receive more informative (ie:
unobfuscated) error messages.
To include the Ext Core library's development version, simply include the
following JavaScript file:
<script src="ext-core-debug.js"></script>
And for the production version (25k compressed and gzipped), simply
remove "-debug":
<script src="ext-core.js"></script>
After you have included Ext Core to your web page, try out the following
code to check if everything working correctly
Ext.onReady(function() {
Ext.DomHelper.append(document.body, {tag: 'p', cls: 'some-class'});
Ext.select('p.some-class').update('Ext Core successfully injected');
});
About
The Ext Core Manual was authored by Tommy Maintz, Aaron Conran, James
Donaghue, Jamie Avins & Evan Trimboli. Thank you to all reviewers who
reviewed the manual prior to its release. We are currently looking for
translations to all other languages.
The Ext Core Manual is licensed under the GNU FDL, GNU Free
Documentation License.
Ext.Element has the most methods out of any class in the Ext Core library.
These methods can be categorized as follows:
var el = Ext.get('myElementId');
Using Firebug, try executing the following code. Observe the methods
exposed by Ext.Element. Remember that because you are looking at the raw
JS Object, both public as well as private methods are visible. When in doubt,
consult the API documentation.
var el = Ext.get('myElementId');
console.dir(el);
var el = Ext.get('myElementId');
el.addClass('error');
After executing this code, the font color in the paragraph above will change
to red. This page has a CSS rule which changes all elements with a class of
error to the color red. The CSS rule looks like this:
.error {
color: red;
}
The next section on Ext.Element (CSS Classes & Styling) will cover many
ways to interact with with your elements' CSS classes and styling.
Ext.fly('myElementId').removeClass('error');
When this code was executed, Ext was able to re-use the existing shared
flyweight object and did not have to instantiate a brand new instance of an
Ext.Element. The fly method is appropriate in situations executing a single,
one-lined, atomic operation. You never want to try to store a reference to
the flyweight object, since it is subject to change by some other snippet of
code. For an example, let's take a look at the following example.
var el = Ext.fly('foo');
Ext.fly('bar').frame();
el.addClass('error');
The answer is that the element with an id of bar will have the frame effect
applied to it and then immediately after it will also have the CSS class of
error applied to it. Nothing will happen to the element with an id of foo,
because the reference el points to the global flyweight which was
overwritten when we used the frame effect on bar. If you did not expect
this, re-read the section about flyweights as it is an important concept if you
wish to use the Ext.fly method.
Ext.get
Ext.getDom
Ext.getDom returns a dom node for the passed in String (id), dom
node, or Ext.Element.
Here are some examples:
We have learned about markup, how that relates to the document and the
methods that Ext Core provides making it easy to retrieve that data. What
about the layout of the document though? How do we manipulate the layout
and styling of the document? The answer is to use Cascading Style Sheets
(CSS) styling. CSS is the language by which we can control layout and visual
information about our page. Ext Core makes it really easy to manipulate the
style of elements in the document through classes or by modifying styles
directly.
<style type="text/css">
myCls {
color: #F00;
}
</style>
...
<div type="myCls">Hello</div>
In the example above the class 'myCls' is applied to the div giving the text
'Hello' a visual color of red (#F00).
Now that we have already learned about firebug, take a look some more of
the wonderful tools that it has to offer us. Right click on any element in the
page and choose "Inspect Element". Now in firebug we can see the dom tree
and where that element is located. If you look to the right of that tree you
will see a panel with all of the styles applied to that element.
If you're not yet familiar with using FireBug, pause now and learn all about it
-- it's the oscilloscope of web-development. Inspect-element comes in handy
for changing styles on an existing site or creating and debugging styles on a
new site. So lets explore the methods that Ext Core provides to make css
modifications easier for you.
addClass
radioClass
Add class in one element and remove that same class if it exists from
all of its siblings in one call.
// add the class 'myCls' to the element and remove that same class from
// all sibilings.
Ext.fly('elId').radioClass('myCls');
removeClass
toggleClass
hasClass
if (Ext.fly('elId').hasClass('myCls')) {
// it has the class
}
replaceClass
Ext.fly('elId').replaceClass('myClsA', 'myClsB');
getStyle
setStyle
Ext.fly('elId').setStyle('color', '#FFFFFF');
Ext.fly('elId').setStyle('z-index', 10);
Ext.fly('elId').setStyle({
display : 'block',
overflow : 'hidden',
cursor : 'pointer'
});
// animate the transition of color
Ext.fly('elId').setStyle('color', '#FFFFFF', true);
// animate the transition of color with a duration of .75 seconds
Ext.fly('elId').setStyle('color', '#FFFFFF', {duration: .75});
// ... etc.
getColor
Gets a normalized (6 digit hex) color value for the passed in property,
accepts a default value if the property is not set and a prefix (# is the
default).
Ext.fly('elId').getColor('background-color');
Ext.fly('elId').getColor('color');
Ext.fly('elId').getColor('border-color');
// ... etc.
setOpacity
Ext.fly('elId').setOpacity(.5);
Ext.fly('elId').setOpacity(.45, true); // animates
// animates with a duration of half a second
Ext.fly('elId').setOpacity(.45, {duration: .5});
clearOpacity
Ext.fly('elId').clearOpacity();
Dom Traversal
Frequently we want to navigate around the dom tree from any given position
that we are working in. Ext Core provides many useful cross browser
methods that give you trememndous power in traversing up, down and all
around the dom. Again CSS comes to the rescue when we want to perform
complex navigations rather easily. The use of CSS3 selectors has a powerful
application in this domain. Take the following markup:
<style type="text/css">
.red {
color: #F00;
}
</style>
...
<div id='elId'>
<ul>
<li>a-one</li>
<li>a-two</li>
<li>a-three</li>
<li>a-four</li>
</ul>
<ul>
<li>b-one</li>
<li>b-two</li>
<li>b-three</li>
</ul>
</div>
Now say you have a requirement to make every other list item have red
text. Ext Core allows you to solve this elegantly with the following one-liner.
Ext.fly('elId').select('li:nth-child(2n)').addClass('red');
Here is the result:
Now that we've seen some of the power in Ext Core's Dom Traversal API,
lets explore more:
is
var el = Ext.get('elId');
if (el.is('p.myCls')) {
// do something
}
findParent
Finds a parent node that matches the selector, starts at the current
node.
findParentNode
Finds a parent node that matches the selector, starts at the parent
node.
Ext.fly('elId').findParentNode('div');
up
Finds a parent node that matches the selector, starts at the parent
node. This returns an Ext.Element
Ext.fly('elId').up('div');
Ext.fly('elId').up('div', 5); // only looks up 5 parents
select
query
Child selects a single child at any given depth below the current
element based on the passed in selector.
down
parent
Gets the parent node for this element. If a selector is passed in it will
go up the chain looking for a match.
prev
first
Manipulation
Elements
In a dynamic page one of the most frequent tasks is to create or remove
elements in the DOM. Due to inconsistencies between browsers this can
prove to be a challenging task. Ext Core provides a stong API that abstracts
these cross browser inconsistencies and is internally optimized for efficiency.
We can easily add, remove or replace nodes in the Dom tree at any position
we want relative to siblings and parents using Ext Core's Dom Manipulation
API. Let's take a look for ourselves -- observe the following markup:
<div id='elId'>
<p>paragraph one</p>
<p>paragraph two</p>
<p>paragraph three</p>
</div>
Here is a screenshot of the markup:
Lets create a new node and insert this as a first child of 'elId':
Ext.fly('elId').insertFirst({
tag: 'p',
html: 'Hi I am the new first child'
});
Easy enough! -- lets explore some of the more powerful mainuplation API's
provided by Ext Core:
appendChild
var el = Ext.get('elId1');
// append the dom node with this id.
Ext.fly('elId').appendChild('elId2');
// append an Ext.Element
Ext.fly('elId').appendChild(el);
// append the result of an array of selectors
Ext.fly('elId').appendChild(['elId2','elId3']);
// append a straight dom node
Ext.fly('elId').appendChild(el.dom);
// append a CompositeElement of all divs
Ext.fly('elId').appendChild(Ext.select('div'));
appendTo
var el = Ext.get('elId1');
insertBefore
var el = Ext.get('elId1');
insertAfter
var el = Ext.get('elId1');
insertFirst
Takes an element, id, or DomHelper config and inserts the existing
node or creates a new element from the DomHelper config as the first
child of this element.
var el = Ext.get('elId1');
replace
var el = Ext.get('elId1');
var el = Ext.get('elId1');
You may have wondered what the 1st argument to insertFirst is. This is a
DomHelper config which represents the markup to be created. DomHelper
configs support many properties for specifying child nodes, such as html
fragments and DomNode attributes (css classes, url, src, id, etc). Here are
some of the API's available on Ext.Element that allow you to interact directly
with Ext.DomHelper:
createChild
var el = Ext.get('elId');
var dhConfig = {
tag: 'p',
cls: 'myCls',
html: 'Hi I have replaced elId'
};
Html Fragments
Html fragments are just what they sound like, fragments of html markup.
Ext Core provides the ability to modify the dom with html fragments,
allowing you to focus upon just those fragments of markup that you intend
to modify the dom with, freeing you from browser implementation and
performance worries. Ext Core does all of that for you -- all you need to do
is provide the markup. For example, given the following markup:
<div id='elId'>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</div>
What do you think the following Ext Core code will do?
Ext.fly('elId').insertHtml('beforeBegin', '<p>Hi</p>')
Lets take a look at the markup afterward:
<p>Hi</p>
<div id='elId'>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</div>
Suprised? That's because we are able to specify the relative position where
we want this markup applied. We specified 'beforeBegin'. What about this:
Ext.fly('elId').insertHtml('afterBegin', '<p>Hi</p>')
The following API is yeaprovided for you to work with html fragments.
insertHtml
Inserts an html fragment into this element. You need to specify where
(beforeBegin, beforeEnd, afterBegin, afterEnd) the fragment and can
optionally specify if you want an Ext.Element returned instead of the
dom node.
Ext.fly('elId').insertHtml(
'beforeBegin',
'<p><a href="anotherpage.html'>click me</a></p>'
); // returns dom node
Ext.fly('elId').insertHtml(
'beforeBegin',
'<p><a href="anotherpage.html'>click me</a></p>',
true
); // returns Ext.Element
remove
Removes this element from the DOM and deletes it from the cache.
removeNode
Removes a DOM node from the document. The body node will be
ignored if passed in.
Ajax
Ext Core includes a powerful Ajax API. Ajax will be covered in greater detail
in later sections but here's a brief overview of the present API in Ext Core:
load
Ext.fly('elId').load({url: 'serverSide.php'})
getUpdater
Event handling poses one of the most troublesome differences among the
browsers. Ext Core abstracts the differences you would encounter to achieve
cross-browser event handling. If you were to use each browser's native
event handling mechanism you need to use different methods to register
and unregister events in addition to a myriad of other frustrating
inconsistencies.
Ext Core provides a rich event model which frees one from these differences
by using a single clean, consistent interface. Just as Ext.Element wraps
around a native Dom node, Ext Core will also wrap the browser's native
event-object with an instance of Ext.EventObject. Ext.EventObject
normalizes cross-browser differences, such as which mouse button is clicked,
keys pressed, mechanisms to stop event-propagation along with a method
to prevent default actions from taking place.
Ext.fly('myEl').on('click', function(e, t) {
// perform an action on click of myEl
// e is an Ext.EventObject describing what occured
// t is the target HTMLElement
});
Ext Core normalizes the arguments of all Dom events. The event handler
which is tied to the event will always receive a normalized event object
(Ext.EventObject) and the target HTMLElement.
Let's take a look at the API provided for Event Handling:
addListener/on
var el = Ext.get('elId');
el.on('click', function(e,t) {
// e is a normalized event object (Ext.EventObject)
// t the target that was clicked, this is an Ext.Element.
// this also points to t.
});
removeListener/un
var el = Ext.get('elId');
el.un('click', this.handlerFn);
// or
el.removeListener('click', this.handlerFn);
Ext.EventObject
Ext Core has several convenience configurations for more advanced event
handling techniques such as event delegation, buffering, and delays.
delegation
This doesn't mean that you want to register one global handler on the
body element, as any action on the page that fired an event would
bubble up to that handler and probably have the reverse effect,
actually degrading performance. This technique is extremely useful in
situations like a drop-down, a calendar, etc. Anywhere you have a
group of elements that can be directly or almost directly contained by
a container element. Lets take a look:
<ul id='actions'>
<li id='btn-edit'></li>
<li id='btn-delete'></li>
<li id='btn-cancel'></li>
</ul>
Ext.fly('btn-edit').on('click, function(e,t) {
// handle the event
});
Ext.fly('btn-delete').on('click, function(e,t) {
// handle the event
});
Ext.fly('btn-cancel').on('click, function(e,t) {
// handle the event
});
Ext.fly('actions').on('click, function(e,t) {
switch(t.id) {
case ''btn-edit':
// handle the event
break;
case 'btn-delete':
// handle the event
break;
case 'btn-cancel':
// handle the event
break;
}
});
Because events bubble up the dom hierarchy, they will reach the
handler that we registered on the 'actions' div. We then use a simple
switch to execute the required code. This approach scales well because
we can add many different child elements and still maintain a single
event handler.
delegate
This is a configuration option that you can pass along when registering
a handler for an event to assist with event delegation. By setting this
configuration option to a simple selector, Ext Core will filter the target
or look for a descendant of the target.
el.on('click', function(e,t) {
// handle click
}, this, {
// will filter target to be a descendant with the class 'clickable'
delegate: '.clickable'
});
hover
Ext Core has a cross browser solution for creating a hover effect. The
hover method will ensure that a function is run when the mouse enters
an element and when the mouse leaves an element. mouseenter and
mouseleave are native Internet Explorer events which will filter
mouseout and mouseover events when you are when working with
child elements. Ext Core implements these events for W3C compliant
browsers so that you can use them in any browser.
removeAllListeners
el.removeAllListeners();
single
This is a configuration option that you can pass along when registering
a handler for the event. When set to true, the handler will fire just
once then automatically remove itself.
el.on('click', function(e,t) {
// handle click
}, this, {
single: true // will remove the event after its first firing.
});
buffer
This is a configuration option that you can pass along when registering
a hanlder for the event. This causes the handler to be scheduled to run
in an Ext.util.DelayedTask delayed by the specified number of
milliseconds. If the event fires again within that time, the original
handler is not invoked, but the new handler is scheduled in its place.
el.on('click', function(e,t) {
// handle click
}, this, {
buffer: 1000 // will delay and buffer the firing of
//this event after its initial fire 1000 miliseconds (or 1 second).
});
delay
This is a configuration option that you can pass along when registering
a hanlder for the event. The number of milliseconds to delay the
invocation of the handler after te event fires.
el.on('click', function(e,t) {
// handle click
}, this, {
// will delay the firing of this event after its initial
// fire 1000 miliseconds (or 1 second).
delay: 1000
});
target
This is a configuration option that you can pass along when registering
a hanlder for the event. If you have a specific target that you want to
handle for only, you can assign a reference of it to this config option
and Ext Core will make sure that your handler gets only calls the
handler when it has reached that node in its bubbling phase.
el.on('click', function(e,t) {
// handle click
}, this, {
// only handles the event when it has bubbled up to the first
'div'.
target: el.up('div')
});
Dimensions & Sizing
Pull up firebug, inspect and element (right click and then click on 'Inspect
Element') and take a look at the right panel and click on "layout". You should
see something like this:
This information is extremely useful since it provides all the dimensions of
the inspected-element. Notice the element has a width of 895px, a height of
1669px, 0px padding all around, 0px border all around and 0px margin. All
this information is available to you through Ext Core's Dimensioning API of
Ext.Element!
var dimSz = Ext.get('dim-sizing');
var padding = dimSz.getPadding('lrtb'); // has value of 0px
var border = dimSz.getBorderWidth('lrtb'); // has value of 0px
var height = dimSz.getHeight(); // has value of 1691px
var width = dimSz.getWidth(); // has value of 895px
Grab this code and run it in firebug to see for yourself. In fact go a step
further and try using the setters to modify the height and width and see
what happens to the box in the firebug layout panel. (NOTE: if your height
and width are different from the image, that is because of the dimensions of
your browser. If you navigate of inspect that element in you actual browser
the outputs should match.)
getHeight
var ht = Ext.fly('elId').getHeight();
getWidth
var wd = Ext.fly('elId').getWidth();
setHeight
Ext.fly('elId').setHeight();
setWidth
Ext.fly('elId').setWidth();
getBorderWidth
Gets the width of the border(s) for the specified side(s). Side can be t,
l, r, b or any combination of those to add multiple values. For
example, passing lr would get the border (l)eft width + the border
(r)ight width.
getPadding
Gets the width of the padding(s) for the specified side(s). Side can be
t, l, r, b or any combination of those to add multiple values. For
example, passing lr would get the padding (l)eft + the padding (r)ight
clip
Store the current overflow setting and clip overflow on the element -
use unclip to remove
Ext.fly('elId').clip();
unclip
Ext.fly('elId').unclip();
isBorderBox
if (Ext.isBorderBox) {
// do something
}
Positioning
Through Ext Core's positioning API it's a snap to get and set all aspects of an
element's position across all browsers. Similar to the dimension API, most of
the setters support animations, either through a boolean true (for defaults)
or by passing an object-literal configuration object as the second argument.
Lets see an example of what this looks like: Lets see an example of what
this looks like:
getY
getXY
setX
Ext.fly('elId').setX(10)
setY
Ext.fly('elId').setY(10)
setXY
Ext.fly('elId').setXY([20,10])
getOffsetsTo
Returns the offsets of this element from the passed element. Both
element must be part of the DOM tree and not have display:none to
have page coordinates.
getLeft
getTop
getBottom
setLeft
Sets the element's left position directly using CSS style (instead of
setX).
Ext.fly('elId').setLeft(25)
setRight
Ext.fly('elId').setRight(15)
setTop
Sets the element's top position directly using CSS style (instead of
setY).
Ext.fly('elId').setTop(12)
setBottom
Ext.fly('elId').setBottom(15)
setLocation
Ext.fly('elId').setLocation(15,32)
moveTo
Ext.fly('elId').moveTo(12,17)
position
Ext.fly('elId').position("relative")
clearPositioning
Clear positioning back to the default when the document was loaded
Ext.fly('elId').clearPositioning()
Ext.fly('elId').clearPositioning("top")
getPositioning
Gets an object with all CSS positioning properties. Useful along with
setPostioning to get snapshot before performing an update and then
restoring the element.
setPositioning
Ext.fly('elId').setPositioning({
left: 'static',
right: 'auto'
})
translatePoints
Translates the passed page coordinates into left/top css values for this
element
Animations
Ext Core has animation plugins available that give you a robust set of
preconfigured animations that are alredy applied as methods to Ext.Element
so you can do cool things like this:
Ext.fly('slideEl').slideOut('r');
Copy the above code, run it in FireBug and see what happens. You will see
below that Ext has a full set of animations already built for you. Each
animation takes a configuration object literal making it very customizable if
you need more than the default behavior. Perhaps you want to add your own
callback function to fire upon completion of the animation:
Ext.fly('slideEl').slideOut('r', {
callback : function(){
alert('Finished sliding the element out');
}
});
So you can see there are some really powerful animations here.
slideIn/slideOut
Fades the element out while slowly expanding it in all directions. When
the effect is completed, the element will be hidden (visibility =
'hidden') but block elements will still take up space in the document.
The element must be removed from the DOM using the 'remove' config
option if desired. Usage:
// default
el.puff();
Blinks the element as if it was clicked and then collapses on its center
(similar to switching off a television). When the effect is completed,
the element will be hidden (visibility = 'hidden') but block elements
will still take up space in the document. The element must be removed
from the DOM using the 'remove' config option if desired. Usage:
// default
el.switchOff();
frame
el.pause(1);
fadeIn/fadeOut
// common config options shown with default values. The height and
width will
// default to the element's existing values if passed as null.
el.scale(
[element's width],
[element's height], {
easing: 'easeOut',
duration: .35
}
);
shift
Slides the element while fading it out of view. An anchor point can be
optionally passed to set the ending point of the effect. Usage:
Complex animations
We can also use the Ext Core animation system to build our own
complex custom animations. Copy the following code into FireBug and
see what it does:
var el = Ext.get('complexEl')
el.animate({
borderWidth: {to: 3, from: 0},
opacity: {to: .3, from: 1},
height: {to: 50, from: el.getHeight()},
width: {to: 300, from: el.getWidth()}
});
Miscellaneous
The following are useful Ext.Element methods which don't fit in the previous
sections but bear mentioning.
focus
Tries to focus the element. Any exceptions are caught and ignored.
el.focus();
blur
Tries to blur the element. Any exceptions are caught and ignored
el.blur();
getValue
el.getValue();
el.getValue(true); // parses the value as a number
isBorderBox
if (Ext.isBorderBox) { }
getAttributeNS
el.getAttributeNS("","name");
What is a Composite?
<html>
<body>
<div id="first" class="title">Sample A</div>
<div id="second" class="doesNotMatch">Lorem Ipsum</div>
<div id="third" class="title secondCSSCls">Some additional
content</div>
</body>
</html>
We could use the CSS selector '.title' to search the entire page and retrieve
a CompositeElement that contains references to the div's first and third.
Note: The element third also has an additional CSS class of secondCSSCls.
HtmlElement's can have multiple CSS classes by separating them with a
space. This selector does not require that only title is applied and therefore
both 'first' and 'third' will be returned.
When you are aware of the location of the elements you want to retrieve
relative to another element on the page you should first obtain a reference
to that element and then search from there. This will make your search
perform faster because it is searching a smaller subset of the entire
document. Let's see what happens when we add an additional div with an id
of 'accordion' wrapping around our first, second and third elements.
<html>
<body>
<div id="accordion">
<div id="first" class="title">Sample A</div>
<div id="second" class="doesNotMatch">Lorem Ipsum</div>
<div id="third" class="title secondCSSCls">
Some additional content
</div>
</div>
</body>
</html>
Since we know that the elements will be within a div with an id of accordion
we can scope our search to only the accordion element.
Any time that you are aware of the location of the elements within your
markup you should make sure that you scope your search like this to
optimize performance.
Ajax Defined
Asynchronous JavaScript and XML (coined AJAX in 2005), is a group of interrelated web development
techniques used to create interactive web applications or rich Internet applications. With Ajax, web
applications can retrieve data from the server asynchronously in the background without interfering
with the display and behavior of the existing page. Data is retrieved using the XHR (XMLHttpRequest)
object. Because of the complexity of handling cross-browser distinctions between XHR
implementations, Ajax frameworks have emerged to abstract these differences into a set of reusable
programming constructs. Within Ext, performing these functions is done within the Ext.Ajax singleton
object.
Ext.Ajax
Ext.Ajax extends the Ext.data.Connection class into a singleton and provides a centralized area to
make Ajax requests with maximum flexibility. By using this singleton, all Ajax requests can be routed
through one class and provide access to all functions, events, and parameters.
Ext.Ajax Events
Ext.Ajax exposes global Ajax events that can be handled on every request.
Since Ext.Ajax is a singleton, you can set properties for it once and override them at the request
function level only if necessary. Common properties you may want to set are:
method: The default HTTP method to be used for requests. Note that this is case-sensitive
and should be all caps (defaults to undefined; if not set but parms are present will use "POST,"
otherwise "GET.")
extraParams: An object containing properties which are used as extra parameters to each
request made by this object (defaults to undefined). Session information and other data that
you need to pass with each request are commonly put here.
url: The default URL to be used for requests to the server (defaults to undefined). If the
server receives all requests through one URL, setting this once is easier entering it on every
request.
defaultHeaders: An object containing request headers which are added to each request
made by this object (defaults to undefined).
Ext.Ajax.request
Ext.Ajax.request is the function called to send and receive data to the server via Ajax. Success and
failure functions can also be set up to handle the response returned by the server. Note that these
success/failure functions are asynchronous and will be called back when the server responds, while
this is happening they webpage will continue to operate.
Ext.Ajax.request({
url: 'ajax_demo/sample.json',
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
console.dir(obj);
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
Ext.Updater
Another common use for Ajax is updating elements dynamically on a page without refreshing
everything. The request method exposes an el configuration which will take the response from a
request and set it to the innerHTML of an element. Developers can also use the Ext.TaskMgr to setup
a recurring task to update the element periodically.
Ext.Ajax.request({
url: 'ajax_demo/sample.json',
form: 'myForm',
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
console.dir(obj);
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
What is DomQuery?
DomQuery provides high performance selector/xpath processing. It works on HTML and XML
documents (if a content node is passed in). DomQuery supports most of the CSS3 selectors spec,
along with some custom selectors and basic XPath. A list of the full CSS3 selector spec can be found
here.
Multiple Selections
You can select multiple sets of at elements with different criteria into a single result set.
// Matches all divs with class foo and all spans with class bar
Ext.select('div.foo, span.bar');
Selection Root
When using a selector, it is possible to specify an optional root node, if it is not specified it will default
to the document body. This can be useful to increase performance, since specifying a root means
there will be possibly less nodes to check.
Selection Chaining
Selectors can be chained to match multiple criteria, which is useful if you need to execute a complex
query. Chained attributes are processed in order
// Matches a div with a class of foo, that has a title attribute bar, that is
// the first child of its immediate parent.
Ext.select('div.foo[title=bar]:first');
Element selectors
* any element
E an element with the tag E
E F All descendent elements of E that have the tag F
E > F or E/F all direct children elements of E that have the tag F
E + F all elements with the tag F that are immediately preceded by an element with the
tag E
E ~ F all elements with the tag F that are preceded by a sibling element with the tag E
Attribute selectors
Pseudo selectors
markup
Same as the deprecated createHtml
insertHtml
insertBefore
insertAfter
insertFirst
append
overwrite
DOM Scripting Ext.DomHelper
href: 'htt
var myDiv = document.createElement('div');
htm
myDiv.id = 'my-div';
tar
myDiv.appendChild(myEl);
document.body.appendChild(myDiv);
DomHelper Configurations
t
<a href="http://www.extjs.com">Ext JS</a> href: 'http
htm
Template
Function Augmentation
The following functions have been added to the Function prototype (note
that createSequence and createInterceptor have not been included):
createCallback
createDelegate
defer
The following methods are added to the Array prototype, if and only if they
are not already implemented by the browser:
indexOf
Finds the first index in the array that matches the passed in
parameter. If not found in the array, -1 is returned.
remove
Removes the first instance of the passed argument from the array, if
found. Note that this modifies the array.
The String class has a single format method added. Note that it may conflict
when using Ajax.NET.
format
var s = String.format(
'Hey {0} {1}', how are you?',
'John',
'Smith'
);
//{0} is substituted with John, {1} is substituted with Smith.
About Utilities
Ext provides a series of general utility functions for working with Javascript
and JSON. They vary in their functionality, but all of them aim to make your
life as the developer easier.
apply
The apply function is used to copy the properties of one object literal
to another. The first argument is the destination object. The second
argument is the source to copy from. Note that all properties in the
source will be copied over, even if they exists in the destination. Also,
the destination object will be modified as a result of calling the
method.
var person = {
name: 'John Smith',
age: 30
};
Ext.apply(person, {
hobby: 'Coding',
city: 'London'
}); // person literal now contains hobby and city as well
applyIf
This function is very similar to apply. The only difference is that applyIf
only copies properties that don't exist in the destination object. If they
already exist in both, the destination object takes precedence and the
property is not copied.
var person = {
name: 'John Smith',
age: 30,
Ext.applyIf(person, {
hobby: 'Coding',
city: 'London'
}); // hobby is not copied over
Url Encoding/Decoding
These methods are useful for transforming JSON data to a format that can
be transmitted as part of a GET string and vice versa.
urlEncode
var params = {
foo: 'value1',
bar: 100
};
var s = 'foo=value1&bar=100';
var o = Ext.decode(s); // o now contains 2 properties, foo and bar.
alert(o.bar);
Array Handling
The core provides methods for working with arrays and other collections
within Javascript.
each
toArray
encode
var s = Ext.encode({
foo: 1,
bar: 2
}); //s now contains '{foo=1,bar=2}'
decode
var s = '{foo=1,bar=2}';
var o = Ext.decode(s); o is now an object with 2 properties, foo and
bar.
Browser & OS Detection
JavaScript
Ext offers a number of browser-detection features allowing developers to
work around implementation issues due to differences between the major
browsers. Ext provides detection in both javascript and css, to allow for
greater functionality in both these areas.
if(Ext.isIE){
// Do browser specific code here
}
CSS
A similar mechanism is applied in the CSS, various class names are added to
the root element and the body depending on the current operating
environment. This allows for easier style rules to get around browser quirks.
If in strict mode, ext-strict is added to the root. The rest of these are added
to the body when appropriate:
isEmpty
alert(Ext.isEmpty(''));
isArray
alert(Ext.isArray([1, 2, 3]));
isObject
alert(Ext.isObject({}));
isFunction
alert(Ext.isFunction(function(){
}));
Miscellaneous
id
The TaskRunner class is used to execute a function at a specified interval. This is useful when doing
polling type operations, for example when reloading Ajax content every 30 seconds. The TaskMgr
object is a singleton instance of TaskRunner, it can be used for quick access to a TaskRunner.
// Using TaskMgr
Ext.TaskMgr.start({
run: function(){
},
interval: 1000
});
DelayedTask
The DelayedTask class provides a convenient way to "buffer" the execution of a method. When called,
the task will wait the specified time period before executing. If durng that time period, the task is
called again, the original call will be cancelled. This continues so that the function is only called a
single time for each iteration. This method is especially useful for things like detecting whether a user
has finished typing in a text field.
Note that we are using a DelayedTask here to illustrate a point. The configuration option buffer for
addListener/on will also setup a delayedtask for you to buffer events.
Class System
JavaScript Classes
Ext.extend
extend
Person = Ext.extend(Object, {
constructor: function(first, last){
this.firstName = first;
this.lastName = last;
}
getName: function(){
return this.firstName + ' ' + this.lastName;
}
});
Developer = Ext.extend(Person, {
getName: function(){
if(this.isCoding){
return 'Go Away!';
}else{
// Access the superclass getName method
return Developer.superclass.getName.call(this);
}
}
});
override
When placing items in the prototype of the prototype, they will be shared
across all instances of the class. Unless you specifically want to do this, you
should only put "primitive" types inside the prototype definition.
MyClass = Ext.extend(Object, {
// This object literal is now shared between all instances of MyClass.
baseParams: {},
foo: function(){
this.baseParams.bar = 'baz';
}
});
Ext.onReady(function(){
a.foo();
// Modifying baseParams in a affects baseParams in b.
console.log(b.baseParams);
});
Singletons
Otherwise known as the module design pattern this pattern allows you to
create private JS Variables or methods through the clever use of closures.
The singleton is a good pattern to use when you you have a class of static
methods, or you have a class that will only be used once. A good candidate
for a singleton is the entry point into your application.
MyApp = function(){
var data; data is private and can't be accessed from outside.
return {
init: function(){
// Initialize application here
},
getData: function(){
return data;
}
};
}();
Ext.onReady(MyApp.init, MyApp);
Ext.util.Observable
The Observable (or subscriber) pattern is used to decouple objects that need
to know details about the state of other objects. It does this by using
events. When the state of the subject changes, the subject will fire an event.
Subscribers to that particular event on the subject will then be notified that
the state change has occurred. Many Ext classes extend Observable to allow
for a flexible, decoupled programming model. You can easily create classes
that fire custom events:
update: function(){
// do some data transformation here
// When firing an event, we can specify what parameters are
// passed to the subscribers.
this.fireEvent('datachanged', this, this.data.length);
}
});
// To subscribe to an event
var c = new MyClass();
c.on('datachanged', function(obj, num){
// react to the data changed event.
});
Namespaces
Namespaces are useful for organizing your code, they provide 2 main
benefits. The first is that you can use them to prevent polluting the global
namespace with objects, which is generally considered to be undesireable.
Ext, for example has just a single global object (the Ext object). It's good
practice to put any classes inside a namespace, a common one is the name
of your company or the name of your application. The other advantage is
that assists in keeping your code organized, you can group together similar
or co-dependent classes in the same namespace, which helps to specify your
intent to other developers.