Skip to content

Feed aggregator

Lanikai Beta 1 preview release is now available for download

Mozilla Developer News - 3 hours 50 min ago

Lanikai Beta 1, available now for download, is built on top of the Gecko 1.9.2 platform. While this milestone is considered to be stable, it is intended for developers and members of our testing community to use for evaluation and feedback. Users of this latest alpha version of Thunderbird should not expect all of their add-ons to work properly with this milestone.

The main goals of this release is to find out about possible problems caused by the changes in the underlying platform. Notable changes include:

  • Several fixes to improve upgrading from Thunderbird 2.
  • Several fixes for auto complete, tabs, and activity manager.
  • Several design improvements and corrections to the interface.
  • Stability and memory improvements.

For a more detailed list of bug fixes, see the the full bug list.

The Rumbling Edge has a more detailed list of notable bug fixes.

Downloading

Please read the release notes before downloading for more information about this release including known issues.

Testers can download Lanikai Beta 1 for Windows, Mac OS X, and Linux in English. Community chat about Lanikai can be followed at GetSatisfaction and on irc.mozilla.org in #thunderbird.

Categories: Open Source

Structuring a Web Page with CSS and ASP.NET

Ajax Alliance Portal - 8 hours 52 min ago
This article explains why such habits as using nested HTML Tables to position content in the right place on the browser page is bad practice and, nowadays, avoidable. It is just one 'Markup smell' that it discusses on the way to demonstrating the ben ...
Categories: Communities

Using Base64 Canvas Data In jQuery To Create ColdFusion Images

Ben Nadel Ajax and JQuery Feed - 9 hours 45 min ago
Last week, I explored the HTML Canvas element for the first time. In that exploration, I created a "finger painting" demo for the iPhone that would post drawing commands to the server where the image would be re-created as a PNG in ColdFusion. That was a nice approach because it gave me some flexibility in how the ColdFusion image was created (using anti-aliasing and a t ... Read More »
Categories: Blogs

CSS3 Please! Instant results… Thank You

Ajaxian - 10 hours 55 min ago

css3please

Paul Irish and Jonathan Neal have created a fun example of various CSS tweaks that you can make, and see the results instantly.

CSS3, Please! lets you play with fancy new rules such as:

  • border-radius
  • box shadow
  • gradients
  • rgba support in backgrounds
  • transforms
  • font-face

Really nice way to make tweaks inline in the page….. nicely done. Hope to see some other examples out there :)

Categories: Communities

HTML Minification

Ajaxian - 13 hours 19 min ago

Good old Kangax has been playing with HTML minification and has shared his new tool in an early stage.

What does it do?

Kangax has forked John Resig’s HTML parser which parses the HTML and sends that into the Minifier. This has rules that do things like whitespace optimization, comment removal, and collapsing boolean attributes (e.g. disabled=”true” -> disabled).

He also has a linter going:

While working on minifier, I realized that oftentimes the most wasteful part of the markup is not white space, comments or boolean attributes, but inline styles, scripts, presentational or deprecated elements and attributes. None of these can be simply stripped, as that could affect state of the document and is just too obtrusive. What can be done, however, is reporting of these occurences to the user. HTMLLint is even a smaller script, whose job is exactly that—to log any deprecated or presentational elements/attributes encountered during parsing. Additionally, it detects event attributes (e.g. onclick, onmouseover, etc.). The rationale for this is that moving contents of event attributes to external script allows to take advantage of resource caching.

Categories: Communities

XAML RadControls Q1 2010 Official

Telerik Blogs - 14 hours 13 min ago

Q1 2010 release focuses on strengthening 3 main aspects of RadControls for Silverlight and RadControls for WPF:

  • Ensuring first-class performance for all data-centric controls through various techniques,
  • Enhancing and polishing RadControls themes
  • Providing highly advanced, enterprise-level features, especially for the data visualization controls 

We know that performance is crucial for line-of-business applications. Therefore, we always make sure that RadControls can help you achieve unmatched performance and this has always been our number one priority. RadControls achieve unbeatable performance through UI and Data Virtualization, Data Sampling and built-in Load On Demand features.

Several of the major controls in the bundles have been enhanced with UI virtualization support – Scheduler, CoverFlow and Book.

As a part of Q1 2010 we also want to bring an unparalleled visual richness to your applications. To achieve that we have done a major rework of all our themes. We used a uniform templating approach across all controls, streamlined naming conventions for resources and delivered a much more consistent look of the controls along the way.

RadControls for WPF bundle has been enriched with two new controls – Map and Book.

 

Another new control has been included in the Q1 2010 release. However, it continues to be in a CTP stage. This is the Transition control. We decided that this is the better way to proceed as we will need some more input from our community on how exactly to develop this control further. Therefore, we will be regularly blogging on the development progress so that we can clearly indicate the direction, in which the control is evolving and gather your feedback on whether this is the best direction.

Our Charting controls for Silverilght and WPF have been advanced with major new features such as Data Sampling, Zooming and Scrolling, Automatic SmartLables positioning, Sorting and Filtering and many more.

The new built-in paging of the GridView control now allows you to page through your data, thus resulting in an event faster and more responsive grid that can easily handle enormously large datasets.

Categories: Companies

Harmony: Canvas Drawing Tool

Ajaxian - 14 hours 44 min ago

Harmony is a new drawing tool, a HTML5/Canvas experiment with great potential. It provides some unique brush styles, and can produce some great-looking charcoal pencil style sketches, among other things. Better to try it out than explain it in words.

Creator Mr. Doob (Richard Cabello) explains how he used Canvas to make it darker the more you draw over it:

The whole thing is quite modular so I can keep adding more brush styles whenever I get inspired. During the process I found out that, for some reason (apparently lack of hardware acceleration), Firefox and Opera do not support context.globalCompositeOperation = ‘darker’. This was on the HTML5 spec before but got removed. Just so you know what I’m talking about, this is like the “multiply” blending in Photoshop. Webkit does support it tho. I hope they put it back on the specs and all browsers support it.

You can also save images using data URI encoding.

As it works on webkit, he made sure it worked on the mobile Android and iPhone browsers. No multi-touch as yet, but the touch UI still makes a nice input mechanism.

harmony

(Thanks FND)

Categories: Communities

RadControls for ASP.NET AJAX Q1 2010 release is out

Telerik Blogs - 16 hours 19 min ago

The new major Q1 2010 release of RadControls for ASP.NET AJAX has just been uploaded on telerik.com. I know that there are many people who would like to download and try out the new controls/features in the release without any further delay, that is why I will spare you the details for now and will let you enjoy it at your own disposal :) The links below will direct you to the main resources that highlight the important parts you would like to take a look at:

 

What's new:
http://www.telerik.com/products/aspnet-ajax/whats-new.aspx

Release notes:
http://www.telerik.com/products/aspnet-ajax/whats-new/release-history/q1-2010-version-2010-1-309.aspx

 

Demos:
http://demos.telerik.com/aspnet-ajax/controls/examples/default/defaultcs.aspx

 

Documentation:
http://www.telerik.com/help/aspnet-ajax/introduction.html

Categories: Companies

Q1 2010 New Feature: Paging with RadGridView for Silverlight and WPF

Telerik Blogs - 16 hours 34 min ago

RadDataPager

We are glad to announce that the Q1 2010 Release has added another weapon to RadGridView’s growing arsenal of features. This is the brand new RadDataPager control which provides the user interface for paging through a collection of data.

The good news is that RadDataPager can be used to page any collection. It does not depend on RadGridView in any way, so you will be free to use it with the rest of your ItemsControl’s if you chose to do so.

Before you read on, you might want to download the samples solution that I have attached. It contains a sample project for every scenario that I will discuss later on. Looking at the code while reading will make things much easier for you. There is something for everyone among the 10 Visual Studio projects that are included in the solution. So go and grab it.

I. Paging essentials

The single most important piece of software concerning paging in Silverlight is the System.ComponentModel.IPagedCollectionView interface. Those of you who are on the WPF front need not worry though. As you might already know, Telerik’s Silverlight and WPF controls is share the same code-base. Since WPF does not contain a similar interface, Telerik has provided its own Telerik.Windows.Data.IPagedCollectionView.

The IPagedCollectionView interface contains several important members which are used by RadGridView to perform the actual paging. Silverlight provides a default implementation of this interface which, naturally, is called PagedCollectionView. You should definitely take a look at its source code in case you are interested in what is going on under the hood. But this is not a prerequisite for our discussion.

The WPF default implementation of the interface is Telerik’s QueryableCollectionView which, among many other interfaces, implements IPagedCollectionView.

II. No Paging

NoPaging

In order to gradually build up my case, I will start with a very simple example that lacks paging whatsoever. It might sound stupid, but this will help us build on top of this paging-devoid example. Let us imagine that we have the simplest possible scenario. That is a simple IEnumerable and an ItemsControl that shows its contents. This will look like this:

No Paging
  1. IEnumerable itemsSource = Enumerable.Range(0, 1000);
  2. this.itemsControl.ItemsSource = itemsSource;

XAML
  1. <Border Grid.Row="0" BorderBrush="Black" BorderThickness="1" Margin="5">
  2.     <ListBox Name="itemsControl"/>
  3. </Border>
  4. <Border Grid.Row="1" BorderBrush="Black" BorderThickness="1" Margin="5">
  5.     <TextBlock Text="No Paging"/>
  6. </Border>

Nothing special for now. Just some data displayed in a ListBox.

The two sample projects in the solution that I have attached are:

  • NoPaging_WPF
  • NoPaging_SL3

With every next sample those two project will evolve in some way or another.

III. Paging simple collections

The single most important property of RadDataPager is its Source property. This is where you pass in your collection of data for paging.

More often than not your collection will not be an IPagedCollectionView. It will either be a simple List<T>, or an ObservableCollection<T>, or anything that is simply IEnumerable. Unless you had paging in mind when you designed your project, it is almost certain that your data source will not be pageable out of the box. So what are the options?

III. 1. Wrapping the simple collection in an IPagedCollectionView

Wrapping

If you look at the constructors of PagedCollectionView and QueryableCollectionView you will notice that you can pass in a simple IEnumerable as a parameter. Those two classes will wrap it and provide paging capabilities over your original data. In fact, this is what RadGridView does internally. It wraps your original collection in an QueryableCollectionView in order to easily perform many useful tasks such as filtering, sorting, and others, but in our case the most important one is paging. So let us start our series of examples with the most simplistic one. Imagine that you have a simple IEnumerable which is the source for an ItemsControl. Here is how to wrap it in order to enable paging:

Silverlight
  1. IEnumerable itemsSource = Enumerable.Range(0, 1000);
  2. var pagedSource = new PagedCollectionView(itemsSource);
  3. this.radDataPager.Source = pagedSource;
  4. this.itemsControl.ItemsSource = pagedSource;

WPF
  1. IEnumerable itemsSource = Enumerable.Range(0, 1000);
  2. var pagedSource = new QueryableCollectionView(itemsSource);
  3. this.radDataPager.Source = pagedSource;
  4. this.itemsControl.ItemsSource = pagedSource;

XAML
  1. <Border Grid.Row="0"
  2.         BorderBrush="Black"
  3.         BorderThickness="1"
  4.         Margin="5">
  5.     <ListBox Name="itemsControl"/>
  6. </Border>
  7. <Border Grid.Row="1"
  8.         BorderBrush="Black"
  9.         BorderThickness="1"
  10.         Margin="5">
  11.     <telerikGrid:RadDataPager Name="radDataPager"
  12.                               PageSize="10"
  13.                              IsTotalItemCountFixed="True"
  14.                              DisplayMode="All"/>

This will do the trick. It is quite simple, isn’t it?

The two sample projects in the solution that I have attached are:

  • PagingSimpleCollectionWithWrapping_WPF
  • PagingSimpleCollectionWithWrapping_SL3

III. 2. Binding to RadDataPager.PagedSource

PagedSource

In case you do not like this approach there is a better one. When you assign an IEnumerable as the Source of a RadDataPager it will automatically wrap it in a QueryableCollectionView and expose it through its PagedSource property. From then on, you can attach any number of ItemsControl’s to the PagedSource and they will be automatically paged. Here is how to do this entirely in XAML:

Using RadDataPager.PagedSource
  1. <Border Grid.Row="0"
  2.         BorderBrush="Black"
  3.         BorderThickness="1" Margin="5">
  4.     <ListBox Name="itemsControl"
  5.              ItemsSource="{Binding PagedSource, ElementName=radDataPager}"/>
  6. </Border>
  7. <Border Grid.Row="1"
  8.         BorderBrush="Black"
  9.         BorderThickness="1"
  10.         Margin="5">
  11.     <telerikGrid:RadDataPager Name="radDataPager"
  12.                               Source="{Binding ItemsSource}"
  13.                              PageSize="10"
  14.                              IsTotalItemCountFixed="True"
  15.                              DisplayMode="All"/>

The two sample projects in the solution that I have attached are:

  • PagingSimpleCollectionWithPagedSource_WPF
  • PagingSimpleCollectionWithPagedSource_SL3
IV. Paging collections implementing IPagedCollectionView

DomainDataSource

Those of you who are using WCF RIA Services should feel very lucky. After a quick look with Reflector or the debugger we can see that the DomainDataSource.Data property is in fact an instance of the DomainDataSourceView class. This class implements a handful of useful interfaces:

Luckily, IPagedCollectionView is among them which lets you do the whole paging in the server. So let’s do this. We will add a DomainDataSource control to our page/window and connect the items control and the pager to it. Here is how to do this:

MainPage
  1. <riaControls:DomainDataSource x:Name="invoicesDataSource"
  2.                               AutoLoad="True"
  3.                               QueryName="GetInvoicesQuery">
  4.     <riaControls:DomainDataSource.DomainContext>
  5.         <services:ChinookDomainContext/>
  6.     </riaControls:DomainDataSource.DomainContext>
  7. </riaControls:DomainDataSource>
  8. <Border Grid.Row="0"
  9.         BorderBrush="Black"
  10.         BorderThickness="1"
  11.         Margin="5">
  12.     <ListBox Name="itemsControl"
  13.              ItemsSource="{Binding Data, ElementName=invoicesDataSource}"/>
  14. </Border>
  15. <Border Grid.Row="1"
  16.         BorderBrush="Black"
  17.         BorderThickness="1"
  18.         Margin="5">
  19.     <telerikGrid:RadDataPager Name="radDataPager"
  20.                               Source="{Binding Data, ElementName=invoicesDataSource}"
  21.                              PageSize="10"
  22.                              IsTotalItemCountFixed="True"
  23.                              DisplayMode="All"/>

By the way, you can replace the ListBox from the above code snippet with any other ItemsControl. It can be RadGridView, it can be the MS DataGrid, you name it. Essentially, RadDataPager is sending paging commands to the the DomainDataSource.Data. It does not care who, what, or how many different controls are bound to this same Data property of the DomainDataSource control.

So if you would like to experiment with this, you can throw in any number of other ItemsControl’s next to the ListBox, bind them in the same manner, and all of them will be paged by our single RadDataPager.

Furthermore, you can throw in any number of RadDataPager’s and bind them to the same property. Then when you page with any one of them will automatically update all of the rest.

The whole picture is simply beautiful and we can do all of this thanks to WCF RIA Services.

The two sample projects (Silverlight only) in the solution that I have attached are:

  • PagingIPagedCollectionView
  • PagingIPagedCollectionView.Web
IV. Paging RadGridView

RadGridView

While you can replace the ListBox in any of the above examples with a RadGridView, RadGridView offers something extra. Similar to the DomainDataSource.Data property, the RadGridView.Items collection implements the IPagedCollectionView interface. So you are already thinking: Then why not bind the Source property of RadDataPager to RadGridView.Items? Well that’s exactly what you can do and you will start paging RadGridView out-of-the-box. It is as simple as that, no code-behind is involved:

MainPage
  1. <Border Grid.Row="0"
  2.         BorderBrush="Black"
  3.         BorderThickness="1" Margin="5">
  4.     <telerikGrid:RadGridView Name="radGridView"
  5.                              ItemsSource="{Binding ItemsSource}"/>
  6. </Border>
  7. <Border Grid.Row="1"
  8.         BorderBrush="Black"
  9.         BorderThickness="1"
  10.         Margin="5">
  11.     <telerikGrid:RadDataPager Name="radDataPager"
  12.                               Source="{Binding Items, ElementName=radGridView}"
  13.                              PageSize="10"
  14.                              IsTotalItemCountFixed="True"
  15.                              DisplayMode="All"/>

The two sample projects in the solution that I have attached are:

  • PagingRadGridView_SL3
  • PagingRadGridView_WPF

With this last example I think I have covered every possible paging combination. In case you would like to see an example of something that I have not covered, please let me know.

Also, make sure you check out those great online examples:

Happy Paging!

Download Full Source Code

Categories: Companies

Can Flash Thrive Going Forward?

Blog - SitePen, Inc. - 17 hours 13 min ago

The short answer: Yes, if it changes its strategy to one that embraces and augments the open web ecosystem, rather than continuing down the path of trying to compete with or replace it.

With the recent anti-Flash, pro-HTML5 buzz caused by the iPad and sites like YouTube offering HTML5-enabled video alternatives, I thought it would be useful to share my thoughts on the opportunities and struggles Adobe faces with the Flash platform. Given my propensity as a strong open-source advocate, it may seem odd that I bother to discuss this, but it’s an interesting thought experiment for me on where Flash still excels compared to the open web, and how it can leverage that to thrive as part of the world going forward.

Developer Tools

Flash plus Illustrator, Catalyst, Flex Builder and the rest of the Adobe CS collection provide a compelling suite of visual tools for building web sites and applications. While there are a number of attempts at building studio tools using open web technologies, they all tend to be component-driven attempts to clone PowerBuilder or Interface Builder for the web. Flash clearly leads the market in animations and the creation of interfaces that are more movie-like in their experience. For example, while it’s possible to create the famous Sports Illustrated tablet UI demo entirely with HTML5 technologies, today it is much easier to build something this visually rich with Flash. Though ironically, it won’t run on the iPad without Flash compiling to a native iPhone app.

Rendering Engine

The Flash player is really just a replacement rendering engine that works on most platforms that don’t begin with a small i. To date, it’s unfortunately been pretty crash-prone on Mac OS X and has trailed behind on Linux. But it has succeeded because it was a useful hack for improving upon the limitations of the world’s worst browsers. On Windows, it is stable and is a significant improvement to Internet Explorer’s rendering engine. Also, somewhat surprising is that in our performance tests, Flash is not actually any faster at drawing or animating objects than Firefox, Safari, or Chrome, meaning that we do not see them leveraging native hardware 2-D and 3-D acceleration APIs, which are starting to arrive in the next version of the major browsers. Which means that the edge Flash player once enjoyed with its rendering engine is no more.

Revision Cycle

Google Chrome Frame has the advantage now in being able to upgrade the host browser much like Flash can. And really, that’s been Flash’s big advantage historically: it could push updates to the world faster than browser vendors. But in the past few years, versions of Flash have actually been released slower than non-Microsoft browsers, which now include reliable auto-update mechanisms. Being able to patch, hack, and fix the web was Flash’s big advantage, and that edge is gone.

Compilation

It’s fairly interesting that Adobe has made it possible to compile Flash apps into native apps for distribution on the Apple App Store. This idea was likely inspired by PhoneGap and Appcelerator’s Titanium. But it raises an interesting question for me: could Flash compile into native HTML5-compliant applications? That would potentially decouple the benefits of the developer tools from the limitations of the player.

Embracing the Open Web

Adobe to date has dabbled in the world of open source, but Google Chrome Frame is its first real competition in the player/plug-in space, because it has two huge advantages (ignoring its disadvantages for now): it’s open-source, and it builds and extends open web protocols like HTML5, JavaScript, SVG, and more. In my opinion, Flex should have extended HTML4 or XHTML instead of being a complete rewrite from the ground up. This would allow any HTML developer to easily jump into it and then take advantage of Flash’s extension. Imagine Flex apps being unobtrusive upgrades to HTML pages, if the flash player is available! Or, imagine including a Dojo HTML fragment for a grid, using a standardized flash grid component, installed as a native component as part of the player, if that was the best rendering engine available!

Pushing the Open Web into Design Tools

As someone that can’t draw a circle in Photoshop or Illustrator, I would love for everything in a PSD or AI file to be represented by HTML/XML and CSS. Developers loathe having to wait for a designer to change text in a graphics file or modify colors in a background image. As good as the open web gets at moving more and more image functionality to native styling, there will always be concepts that cannot easily be represented tersely enough in the CSS layer. The authoring tools layer is likely the best place to make such modifications. Providing a simple tool or mechanism for developer’s to update or modify files created by designers would be useful and intriguing.

License Pricing

Given the dramatic reduction in costs of computers and software, Adobe is significantly more expensive relative to the cost of other products than it was when it started its CS pricing model. To fix this problem, Adobe has been experimenting with a subscription pricing model in Australia that allows users to pay each month to use the software. That’s more inline with expectations today as it doesn’t require a huge up-front cost. Also, Adobe could start to consider licensing affordable Flash components that are hosted on a CDN, or a number of other fine-grained payment models.

Conclusions

The open web has quickly closed the gap on Adobe’s advantages over the past two years, but there are many new opportunities for Adobe to exist and thrive in the open web ecosystem, and take advantage of the new possibilities this creates, if it can adapt to the completely new world of today’s modern web platforms.

Related posts:

  1. Flash, Silverlight and the Open Web
  2. Porting Dojo Methods to Flash – Part 1 of 3
  3. Lets. Push. Things. Forward.

Categories: Companies

LinkedIn .NET User Group Online Presentation Tomorrow

Official Gaiaware Blog - Tue, 03/09/2010 - 23:54

We will hold an online, free presentation showing what you can do with Gaia Ajax when building next generation web applications in a fast, lightfoot and intelligent way. Jan Blomquist will demonstrate the power of our latest 3.6 version and why abstracting away JavaScript and developing in a managed language is crucial for time-to-market.

5 winners will be chosen at random from the list of attendees. Each of them will win an annual subscription of Gaia Ajax (worth $595).

Wednesday March 10, 2010, 11:00AM (PST)
Get local time

LIDNUG event info

Direct link to Live Meeting

 

 

 

Categories: Companies

YUI Theater — Douglas Crockford: “Crockford on JavaScript — Episode IV: The Metamorphosis of Ajax” (93 min.)

Yahoo! User Interface Blog - Tue, 03/09/2010 - 22:40

Douglas Crockford delivers the fourth lecture in his his Crockford on JavaScript lecture series at Yahoo on March 3, 2010.

Last week, Yahoo! JavaScript architect Douglas Crockford delivered the fourth installment of his Crockford on JavaScript series:

  1. Volume One: The Early Years
  2. Chapter 2: And Then There Was JavaScript
  3. Act III: Function the Ultimate
  4. Episode IV: The Metamorphosis of Ajax
  5. Part V: The End of All Things (March 31 — RSVP)

In this session, Douglas tackles the DOM. On the one hand there was JavaScript, he says, and JavaScript is “what made the browser work.”

On the other hand, there was the Document Object Model, also known affectionately as the DOM. It is what most people hate when they say they hate JavaScript. Most of the people who say they hate JavaScript don’t know JavaScript, might have never seen JavaScript, but they’ve felt the DOM alright. If you don’t know what the difference is and you say, “JavaScript is the stupidest thing I’ve ever seen,” you’re not talking about JavaScript, you’re talking about the DOM. The DOM is the browser’s API. It is the interface. It provides JavaScript for manipulating documents.

The DOM may be imperfect, but it’s nonetheless crucial to what frontend engineers do when they write web applications. In this talk, Douglas provides an overview, situated historically, of where the DOM came from, how it achieved ascendance with Ajax, and what the future might hold. In Douglas’s inimitable fashion, this history starts with Sir John Harrington and takes us up to the present day. A few choice words for CSS are among the many applause lines for veteran developers:

I find within the community of people who use CSS great affection for it. They’re totally invested in CSS, they love it. They can’t imagine any other way of doing formatting in a document. It’s it. It’s sort of like watching an episode of Cops where the cops come in and break up the family dispute, and there’s this “CSS ain’t bad, you just don’t understand it like I do. I know it hurts me, but I make mistakes, I’m wrong.” CSS is awful, and it amazes me the way people get invested in it. It’s like once you figure it out, kind of go “oh, OK, I see how I might be able to make it work,” then you flip from hating it to loving it, and despising anybody who hasn’t gone through what you’ve gone through. It doesn’t make sense to me.

If the video embed below doesn’t show up correctly in your RSS reader of choice, be sure to click through to watch the high-resolution version of the video on YUI Theater.

Other Recent YUI Theater Videos: Subscribing to YUI Theater:
Categories: Companies

Sinasi is Not a SproutCore IDE

SproutCore - Tue, 03/09/2010 - 20:42
Sinasi is Not a SproutCore IDE:

If you love emacs and you love SproutCore, Sinasi will make your data complete.

Categories: Open Source

OpenLaszlo <view>: March 2010 Edition

OpenLaszlo Project Blog - Tue, 03/09/2010 - 20:25

The March edition of the OpenLaszlo <view> is available here:

http://www.openlaszlo.org/misc/OpenLaszloView030910.pdf

Categories: Open Source

Announcing Ext JS 3.2 beta – Multisort, Transitions and Composite Fields

Ext JS - Tue, 03/09/2010 - 19:01

We are pleased to announce that a beta version of Ext JS 3.2 is now publicly available. 3.2 introduces a number of exciting new components and adds great new capabilities to your existing applications.

Categories: Companies

Translating Global jQuery Event Coordinates To A Local Context

Ben Nadel Ajax and JQuery Feed - Tue, 03/09/2010 - 16:31
When you use jQuery to capture mouse events (mousedown, mouseup, click, etc.), the jQuery Event object contains the X and Y coordinates of the mouse position at the time the event was triggered. These coordinates, while somewhat different in each browser, have been standardized by jQuery to be available in the pageX and pageY properties . No matter what the target of the event is, these ... Read More »
Categories: Blogs

Custom events in JavaScript

NCZOnline - Nicholas C. Zakas - Tue, 03/09/2010 - 15:00

Without a doubt, the most often-used paradigm in JavaScript is events. Events are a manifestation of the observer pattern, a well-defined computer science design pattern for loose coupling. Loose coupling is incredibly important for creating maintainable, stable codebases. I talk a lot about loose coupling and its importance in my talk, Scalable JavaScript Application Architecture (video), so I won’t talk too much about it here. However, the concept is very important to grasp if you wish to progress as a software engineer.

Events

Unless you’ve never written any JavaScript before, you’ve used events at some point in time (admittedly, if you’ve never written JavaScript before, the chances of your reading my blog are probably pretty slim). Put quite simply: the way that you tie behavior to web pages is through events. Events are a way of letting interested parties know that an important moment has occurred in the lifecycle of the application. For instance:

window.onload = function(){
    Application.init();
};

In this example, the load event is the interesting moment. I want to know when the window is fully loaded so that I can initialized the JavaScript application. The onload event handler is the location to where an event handler is assigned. The brilliant part is that window doesn’t care what web page is loaded or who is writing the code; it just knows that there’s a function to call when load occurs. This is the essence of loose coupling: when parts of an application have very limited knowledge of one another.

The Browser Object Model (BOM) and Document Object Model (DOM) publish events to allow developers access to the interesting moments of the browser and web page, respectively.

Custom events

It’s no surprise that most JavaScript libraries rely heavily on custom events since this is a pattern that web developers are familiar with. Every major JavaScript library provides its own events, components to enable easy custom event definition, or both. This makes sense, of course, since libraries want to be loosely-coupled to the execution environment, and therefore, to your code.

There’s nothing magic about custom events, though, and there’s no need to load an entire library if you’d like to experiment with custom events. An object that supports custom events needs to be able to do a small set of things:

  1. Assign an event handler for a particular event.
  2. Remove an event handler for a particular event.
  3. Fire an event and call all assigned event handlers.

The following implements all of this basic functionality:

//Copyright (c) 2010 Nicholas C. Zakas. All rights reserved.
//MIT License

function EventTarget(){
    this._listeners = {};
}

EventTarget.prototype = {

    constructor: EventTarget,

    addListener: function(type, listener){
        if (typeof this._listeners[type] == "undefined"){
            this._listeners[type] = [];
        }

        this._listeners[type].push(listener);
    },

    fire: function(event){
        if (typeof event == "string"){
            event = { type: event };
        }
        if (!event.target){
            event.target = this;
        }

        if (!event.type){  //falsy
            throw new Error("Event object missing 'type' property.");
        }

        if (this._listeners[event.type] instanceof Array){
            var listeners = this._listeners[event.type];
            for (var i=0, len=listeners.length; i < len; i++){
                listeners[i].call(this, event);
            }
        }
    },

    removeListener: function(type, listener){
        if (this._listeners[type] instanceof Array){
            var listeners = this._listeners[type];
            for (var i=0, len=listeners.length; i < len; i++){
                if (listeners[i] === listener){
                    listeners.splice(i, 1);
                    break;
                }
            }
        }
    }
};

The EventTarget type has three methods: addListener(), fire(), and removeListener.

The addListener() uses the private _listeners object to store event handlers for various events. When an event handler is added, the method first checks to see if there’s a named property for that event type on the _listeners object, and if not, creates one containing an array. The event handler function is then saved to the array for later.

The fire() method fires an event with a given name. In effect, this method’s only job is to execute each event handler for the given event type. The method accepts either an object, in which case it’s expected to have a type property, or a string, in which case a new object is created and the string is assigned as the value of type. Next, if the event object doesn’t have a target property assigned, it is set to the current instance. This effectively creates an event object similar to the one most are familiar with via the BOM and DOM. Once the event object is created, the _listeners object is checked for event handlers, and if found, they are executed. Note that in order to mimic the BOM/DOM approach, event handlers are executed in the scope of this via the call() method.

The last method, removeListener(), simply reverses the process of addListener(). It searches through the _listeners property for the given event type to locate the specified event handler. If found, the event handler is removed by using the array’s splice() method, and otherwise it exits without doing anything.

Basic usage:

var target = new EventTarget();
function handleEvent(event){
    alert(event.type);
};

target.addListener("foo", handleEvent);
target.fire({ type: "foo" });    //can also do target.fire("foo")
target.removeListener("foo", handleEvent);

Practically speaking, you’ll likely not want to use an instance of EventTarget directly, but rather inherit from it:

function MyObject(){
    EventTarget.call(this);
}

MyObject.prototype = new EventTarget();
MyObject.prototype.constructor = MyObject;
MyObject.prototype.foo = function(){
    this.fire("foo");
};

var o = new MyObject();

o.addListener("foo", function(){
    alert("Foo just happened.");
});

o.foo();

Typically, events are fired in reaction to some other method call, as in this example (events are usually not fired external to the object that is publishing the events).

What about…?

This is a pretty barebones implementation of a custom event providing object, so inevitably someone will come along and ask why I didn’t include one feature or another. There are, of course, a lot of enhancements you can make to custom events if you so desire. Some enhancements others have implemented:

  • Bubbling of events
  • Continue to execute event handlers even if one throws an error
  • Allow event handlers to cancel further processing or default actions

Each of these can be built pretty easily on top of the base presented in this post.

Conclusion

Custom events are a very powerful and useful pattern in JavaScript programming, and your usage of them doesn’t have to rely on a large JavaScript library. Implementing your own custom events is easy. The implementation presented in this post is a minimum feature set that typically fulfills most requirements, but you can consider it as a starting point for more advanced functionality if your requirements are more complex.
Related posts

P.S. My new book, High Performance JavaScript is coming out in early 2010. Need help now? Check out Professional JavaScript, 2nd Edition.

Categories: Blogs

J4D update: My Book, Other Books, Workshops and talks

jQuery for Designers - Remy Sharp - Tue, 03/09/2010 - 15:00
It’s been a while since I’ve been in touch, so I wanted to let you know what’s going on in the jQuery for Designers world, what to look out for and what’s coming next. A personal update I realise I’ve neglected you again (there was a similar dip back in Feb 2009: I see a pattern emerging), [...]
Categories: Blogs

Appcelerator Titanium Releases for General Availability

Ajax Alliance Portal - Tue, 03/09/2010 - 13:39
MOUNTAIN VIEW, CALIF. – March 8, 2010 – Appcelerator®, the leading platform for rapidly developing native mobile, desktop, and iPad applications using web technologies, announced today the release of its flagship product, Appcelerator ...
Categories: Communities