The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect [email protected].

42
The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect [email protected]

Transcript of The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect [email protected].

Page 1: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

The Microsoft AJAX Library

Jeff ProsiseCofounder, Wintellect

[email protected]

Page 2: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Microsoft AJAX Library

ArchitectureArchitecture

Browsers (IE, Firefox, Safari, others)

Browser CompatibilityBrowser Compatibility

Asynchronous CommunicationsAsynchronous Communications

Script Core LibraryScript Core Library

Base Class LibraryBase Class Library

XHTML/CSS Server Scripts

JSONSerializer

JSONSerializer

WebServiceProxies

WebServiceProxies

XML-HTTPStack

XML-HTTPStack

Page 3: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

JavaScript FrameworkJavaScript Framework

• Microsoft AJAX Library is a JavaScript framework– Global functions ($ functions)– JavaScript base type extensions– JavaScript type system– Core classes, interfaces, and other types (script

core)– More classes, interfaces, and other types (BCL)

• JavaScript framework adds value to JavaScript– Adds OOP to JavaScript– Makes JavaScript an easier and more productive

environment in which to work

Page 4: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Global FunctionsGlobal Functions

• Helper functions for use anywhere, anytime

• Used in JavaScript emitted by server controlsFunction Description

$create Creates and initializes a component

$find Retrieves the component with the specified ID

$get Retrieves the DOM element with the specified ID

$addHandler(s) Registers handlers for DOM event(s)

$removeHandler Unregisters a handler for a DOM event

$clearHandlers Unregisters handlers for DOM events

Page 5: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

$get and $create$get and $create

You write this:

<asp:DragOverlayExtender ID="DragOverlayExtender1" TargetControlID="Target" Enabled="true" Runat="server" />

DragOverlayExtender emits this:

$create(Sys.Preview.UI.FloatingBehavior, {"handle":$get('Target')}, null, null, $get('Target'));

$create(Sys.Preview.UI.FloatingBehavior, {"handle":$get('Target')}, null, null, $get('Target'));

Page 6: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

JavaScript Base Type JavaScript Base Type ExtensionsExtensions• Microsoft AJAX Library extends the following

JavaScript types by adding new functions– Array - add, addRange, contains, insert, remove,

etc.– Boolean - parse– Date - format, parselocale, parseInvariant, parse– Error - argumentOutOfRange, invalidOperation, etc.– Number - format, parseLocale, parseInvariant– Object - getType, getTypeName– String - format, endsWith, startWith, trim, etc.

• See http://ajax.asp.net/docs/ClientReference/-Global/JavascriptTypeExtensions/default.aspx

Page 7: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

String.FormatString.Format

var s = String.format ('{0}, {1}, and {2}', 1, 2, 3);window.alert (s);

Page 8: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Adding OOP to JavaScriptAdding OOP to JavaScript

• JavaScript is object-based but not object-oriented

• Microsoft AJAX Library adds OOP to JavaScript– Namespaces– Classes– Inheritance– Interfaces– Enumerated types

• prototype property forms basis for "classes"• Type class provides typing and type reflection

Page 9: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

JavaScript "Classes"JavaScript "Classes"

Person = function(name) { this._name = name;}

Person.prototype = { get_name: function() { return this._name; }

// Declare other class methods here}

Page 10: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Using the Person ClassUsing the Person Class

var p = new Person('Jeff');

// Displays "Jeff"window.alert(p.get_name());

Page 11: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Type ClassType Class

• Adds typing and type reflection to JavaScript

• Adds key instance methods to all types– registerClass, registerInterface– initializeBase, getBaseType– getBaseMethod, callBaseMethod, and others

• Implements key "static" type-related methods– registerNamespace– isNamespace, isClass, isInterface, and others

• Implemented in MicrosoftAjax.js

Page 12: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Registering Namespaces and Registering Namespaces and ClassesClassesType.registerNamespace('Wintellect'); Wintellect.Person = function(name) { this._name = name;}

Wintellect.Person.prototype = { get_name: function() { return this._name; }}

Wintellect.Person.registerClass('Wintellect.Person');

Page 13: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Using Wintellect.PersonUsing Wintellect.Person

var p = new Wintellect.Person('Jeff');

// Displays "Jeff"window.alert(p.get_name());

// Displays "Wintellect.Person"window.alert(Object.getTypeName(p));

Page 14: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Deriving from Deriving from Wintellect.PersonWintellect.PersonWintellect.Programmer = function(name, language) { Wintellect.Programmer.initializeBase(this, [name]); this._language = language;} Wintellect.Programmer.prototype = { get_name: function() { var name = Wintellect.Programmer.callBaseMethod (this, 'get_name'); return name + ' (Programmer)'; }, get_language: function() { return this._language; }}

Wintellect.Programmer.registerClass ('Wintellect.Programmer', Wintellect.Person);

Page 15: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Using Using Wintellect.ProgrammerWintellect.Programmervar p = new Wintellect.Programmer('Jeff', 'C#');

// Displays "Jeff (Programmer)"window.alert(p.get_name());

// Displays "C#"window.alert(p.get_language());

// Displays "Wintellect.Programmer"window.alert(Object.getTypeName(p));

Page 16: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

MicrosoftAjax.jsMicrosoftAjax.js

String-Builder

String-Builder

Sys

WebRequest-Executor

WebRequest-Executor

Sys.Net

_ProfileService_ProfileService

Sys.Services

JavaScript-Serializer

JavaScript-Serializer

Sys.Serialization

DOMElementDOMElement

Sys.UI

_Debug_Debug

EventArgsEventArgs

ComponentComponent

_Application_Application

XMLHttp-EXecutor

XMLHttp-EXecutor

_WebRequest-Manager

_WebRequest-Manager

WebRequestWebRequest

WebService-Proxy

WebService-Proxy

WebService-Error

WebService-Error

OtherOther

ProfileGroupProfileGroup

_Authentication-Service

_Authentication-Service

DOMEventDOMEvent

BehaviorBehavior

ControlControl

PointPoint

BoundsBounds

_Timer_Timer

CultureInfoCultureInfo

OtherOther

Page 17: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

StringBuilderStringBuilder

var sb = new Sys.StringBuilder();

for (var i = 1; i <= 100; i++){ sb.append(i); // Count from 1 to 100 sb.append('<br/>');}

var text = sb.toString(); // Get the results

Page 18: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

_Debug Class_Debug Class

• Debugging class included in script core– "assert" method asserts that a condition is true– "fail" method breaks into the debugger– "trace" method writes trace output– "traceDump" dumps an object to trace output

• Global instance available through Sys.Debug

// In MicrosoftAjax.jsSys.Debug = new Sys._Debug();

Page 19: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Using Sys.DebugUsing Sys.Debug

// Assertvar happy = false;Sys.Debug.assert(happy == true, 'happy is NOT true', false);

// Break into the debuggerSys.Debug.fail('Somebody is NOT happy');

Page 20: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

PreviewWebForms.jsPreviewWebForms.js

• Partial-page rendering support– Sys.WebForms namespace

• PageRequestManager class– Client-side counterpart to UpdatePanel– Manages async callbacks used for partial-page

rendering and performs content updates using results

– Client-side OM enables advanced UpdatePanel customizations not possible from server side

• _UpdateProgress class

Page 21: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

PageRequestManager PageRequestManager MethodsMethods• Provide programmatic control over client-

side PageRequestManager

Method Description

get_isInAsyncPostBack Indicates whether async callback is in progress

getInstance Returns reference to current PageRequestManager instance

abortPostBack Cancel the async callback that is currently in progress

add_* Registers handlers for PageRequestManager events

remove_* Deregisters handlers for PageRequestManager events

Page 22: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

PageRequestManager PageRequestManager EventsEvents• PageRequestManager fires client-side

events• Hook events on client for advanced

customizationsEvent Description

initializeRequest Fired before async callback commences

beginRequest Fired when async callback commences

pageLoading Fired following an async callback (before content is updated)

pageLoaded Fired following a postback or callback (after content is updated)

endRequest Fired when async callback completes

Page 23: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Canceling UpdatesCanceling Updates

<asp:Button ID="CancelButton" Runat="server" Text="Cancel" OnClientClick="cancelUpdate(); return false" /> . . .<script type="text/javascript">function cancelUpdate(){ var obj = Sys.WebForms.PageRequestManager.getInstance(); if (obj.get_isInAsyncPostBack()) obj.abortPostBack();}</script>

Page 24: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

PageRequestManager

Page 25: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

PreviewScript.jsPreviewScript.js

BindingBaseBindingBase

Sys.Preview Sys.Preview.UI

DataControlDataControl

Sys.Preview.Data

DataColumnDataColumn

Sys.Preview.UI.Data

ServiceMethod-Request

ServiceMethod-Request

OtherNamespaces

BindingBinding

ActionAction

InvokeMethod-Action

InvokeMethod-Action

SetProperty-Action

SetProperty-Action

ColorColor

ValidatorValidator

LabelLabel

ButtonButton

CheckBoxCheckBox

DataNavigatorDataNavigator

ItemViewItemView

ProfileProfile

TimerTimer

CounterCounter

OtherOther

TextBoxTextBox

SelectorSelector

OtherOther

ListViewListView

XSLTViewXSLTView

OtherOther

DataRowDataRow

DataTableDataTable

DataViewDataView

DataFilterDataFilter

DataSourceDataSource

OtherOther

OtherOther

Page 26: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Sys.Preview.UISys.Preview.UI

• Classes that abstract HTML control elements– Button, Label, TextBox, Selector, etc.

• Base functionality defined in Sys.UI.Control– get_visible, set_visible– get_parent, set_parent– And so on

• Control classes simplify JavaScript and facilitate browser independence

Page 27: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Using Control ClassesUsing Control Classes

<input type="text" id="Input" />&nbsp;<input type="button" id="MyButton" value="Click Me" />&nbsp;<span id="Output" /> ...<script type="text/javascript">var g_textBox;var g_label;

function pageLoad() { g_textBox = new Sys.Preview.UI.TextBox($get('Input')); var button = new Sys.Preview.UI.Button($get('MyButton')); g_label = new Sys.Preview.UI.Label($get('Output')); button.initialize(); button.add_click(onClick);}

function onClick(){ g_label.set_text(g_textBox.get_text());}</script>

Page 28: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

XML ScriptXML Script

• Alternative to imperative JavaScript– The "other way" to program the Microsoft AJAX

Library

• Supporting infrastructure found in PreviewScript.js– XML parser translates declarations into actions<script type="text/xml-script">

<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">

<!-- XML script goes here -->

</page></script>

Page 29: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Using Control Classes (XML Using Control Classes (XML Script)Script)<input type="text" id="Input" />&nbsp;<input type="button" id="MyButton" value="Click Me" />&nbsp;<span id="Output" /> <script type="text/xml-script"> <page xmlns:script="http://schemas.microsoft.com/xml-script/2005"> <components> <textBox id="Input" /> <button id="MyButton"> <click> <invokeMethodAction target="TextBinding" method="evaluateIn" /> </click> </button> <label id="Output"> <bindings> <binding id="TextBinding" dataContext="Input" dataPath="text" property="text" automatic="false" /> </bindings> </label> </components> </page></script>

Page 30: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Sys.Preview.[UI.].DataSys.Preview.[UI.].Data

• Contains classes that support rich client-side data binding

• ItemView and ListView do client-side rendering

• DataSource links data consumers to data service and supports 2-way data binding

DataControlDataControl

Sys.Preview.Data

DataColumnDataColumn

Sys.Preview.UI.Data

DataNavigatorDataNavigator

ItemViewItemView

ListViewListView

XSLTViewXSLTView

OtherOther

DataRowDataRow

DataTableDataTable

DataViewDataView

DataFilterDataFilter

DataSourceDataSource

OtherOther

Page 31: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

ListView and DataSourceListView and DataSource

<div id="Books"></div><div style="display: none;"> <div id="LayoutTemplate"> <ul id="ItemTemplateParent"> <li id="ItemTemplate"><span id="BookTitle"></span></li> </ul> </div></div>

<script type="text/xml-script"> <page xmlns:script="http://schemas.microsoft.com/xml-script/2005"> <components> <dataSource id="BooksDataSource" serviceURL="Books.asmx" autoLoad="true" /> <listView id="Books" itemTemplateParentElementId="ItemTemplateParent"> <bindings> <binding dataContext="BooksDataSource" dataPath="data" property="data" /> </bindings> <layoutTemplate> <template layoutElement="LayoutTemplate" /> </layoutTemplate> <itemTemplate> ... </itemTemplate> </listView> </components> </page></script>

Page 32: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Data ServiceData Service

[ScriptService]public class Books : DataService{ [WebMethod] [DataObjectMethod(DataObjectMethodType.Select)] public Book[] GetTitles() { // TODO: Generate and return Book array }}

public class Book{ private string _title;

[DataObjectField(true)] public string Title { get { return _title; } set { _title = value; } }}

Page 33: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Enabling Data BindingEnabling Data Binding

• Register JSON converters in Web.config

<system.web.extensions> <scripting> <webServices> <jsonSerialization> <converters> <add name="DataSetConverter"type="Microsoft.Web.Preview.Script.Serialization.Converters.DataSetConverter, ..." /> <add name="DataRowConverter"type="Microsoft.Web.Preview.Script.Serialization.Converters.DataRowConverter, ..." /> <add name="DataTableConverter"type="Microsoft.Web.Preview.Script.Serialization.Converters.DataTableConverter, ..." /> </converters> </jsonSerialization> </webServices> </scripting></system.web.extensions>

Page 34: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Client-Side Data Binding

Page 35: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

PreviewDragDrop.jsPreviewDragDrop.js

• Adds drag-drop support to BCL– Sys.Preview.UI namespace

• _DragDropManager provides core support– Global instance named DragDropManager

• IDropSource and IDropTarget interfaces define signatures for drop-source and drop-target classes

• DragDropList and DraggableListItem provide canned implementation of reorderable lists

• FloatingBehavior provides generic mechanism for floating images, DIVs, and other entities

Page 36: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Floating an ImageFloating an Image

<img id="FloatMe" src="..."> ...<script type="text/javascript">function pageLoad(){ var float = new Sys.Preview.UI.FloatingBehavior ($get('FloatMe')); float.set_handle($get('FloatMe')); float.initialize();}</script>

Page 37: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Floating an Image (XML Floating an Image (XML Script)Script)<img id="FloatMe" src="..."> ...<script type="text/xml-script"> <page xmlns:script="http://.../xml-script/2005"> <components> <image id="FloatMe"> <behaviors> <floatingBehavior handle="FloatMe" /> </behaviors> </image> </components> </page></script>

Page 38: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Drag-and-Drop

Page 39: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

PreviewGlitz.jsPreviewGlitz.js

• Adds UI enhancements to BCL– Sys.Preview.UI.Effects namespace

• OpacityBehavior class wraps opacity of elements

• LayoutBehavior class wraps layout (size and pos)

• Animation and derivatives support animations

Property-Animation

Property-Animation

Interpolated-Animation

Interpolated-Animation

Discrete-Animation

Discrete-Animation

Number-Animation

Number-Animation

Length-Animation

Length-Animation

Composite-Animation

Composite-Animation

Fade-Animation

Fade-Animation

Page 40: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Fading In an ImageFading In an Image

<img id="SplashImage" src="..."> ...<script type="text/javascript">function pageLoad(){ var image = new Sys.Preview.UI.Image ($get('SplashImage')); var fade = new Sys.Preview.UI.Effects.FadeAnimation(); fade.set_target(image); fade.set_effect (Sys.Preview.UI.Effects.FadeEffect.FadeIn); fade.set_duration(3); fade.set_fps(20); fade.play();}</script>

Page 41: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Fading In an Image (XML Fading In an Image (XML Script)Script)<img id="SplashImage" src="..."> ...<script type="text/xml-script"> <page xmlns:script="http://.../xml-script/2005"> <components> <image id="SplashImage" /> <fadeAnimation id="fade" target="SplashImage" effect="FadeIn" duration="3" fps="20" /> <application> <load> <invokeMethodAction target="fade" method="play" /> </load> </application> </components> </page></script>

Page 42: The Microsoft AJAX Library Jeff Prosise Cofounder, Wintellect jeffpro@wintellect.com.

Discussion