Building a data-driven image carousel with Sencha Touch 2
February 11, 2012 by Ed Spencer · 5 Comments
This evening I embarked on a little stellar voyage that I’d like to share with you all. Most people with great taste love astronomy and Sencha Touch 2, so why not combine them in a fun evening’s web app building?
NASA has been running a small site called APOD (Astronomy Picture Of the Day) for a long time now, as you can probably tell by the awesome web design of that page. Despite its 1998-era styling, this site incorporates some pretty stunning images of the universe and is begging for a mobile app interpretation.
We’re not going to go crazy, in fact this whole thing only took about an hour to create, but hopefully it’s a useful look at how to put something like this together. In this case, we’re just going to write a quick app that pulls down the last 20 pictures and shows them in a carousel with an optional title.
Here’s what it looks like live. You’ll need a webkit browser (Chrome or Safari) to see this, alternatively load up http://code.edspencer.net/apod on a phone or tablet device:
The full source code for the app is up on github, and we’ll go through it bit by bit below.
The App
Our app consists of 5 files:
index.html, which includes our JavaScript files and a little CSS
app.js, which boots our application up
app/model/Picture.js, which represents a single APOD picture
app/view/Picture.js, which shows a picture on the page
app/store/Pictures.js, which fetches the pictures from the APOD RSS feed
The whole thing is up on github and you can see a live demo at http://code.edspencer.net/apod. To see what it’s doing tap that link on your phone or tablet, and to really feel it add it to your homescreen to get rid of that browser chrome.
The Code
Most of the action happens in app.js, which for your enjoyment is more documentation than code. Here’s the gist of it:
/* * This app uses a Carousel and a JSON-P proxy so make sure they're loaded first */Ext.require([ 'Ext.carousel.Carousel', 'Ext.data.proxy.JsonP']);
/** * Our app is pretty simple - it just grabs the latest images from NASA's Astronomy Picture Of the Day * (http://apod.nasa.gov/apod/astropix.html) and displays them in a Carousel. This file drives most of * the application, but there's also: * * * A Store - app/store/Pictures.js - that fetches the data from the APOD RSS feed * * A Model - app/model/Picture.js - that represents a single image from the feed * * A View - app/view/Picture.js - that displays each image * * Our application's launch function is called automatically when everything is loaded. */Ext.application({ name: 'apod', models: ['Picture'], stores: ['Pictures'], views: ['Picture'], launch: function() { var titleVisible = false, info, carousel; /** * The main carousel that drives our app. We're just telling it to use the Pictures store and * to update the info bar whenever a new image is swiped to */ carousel = Ext.create('Ext.Carousel', { store: 'Pictures', direction: 'horizontal', listeners: { activeitemchange: function(carousel, item) { info.setHtml(item.getPicture().get('title')); } } }); /** * This is just a reusable Component that we pin to the top of the page. This is hidden by default * and appears when the user taps on the screen. The activeitemchange listener above updates the * content of this Component whenever a new image is swiped to */ info = Ext.create('Ext.Component', { cls: 'apod-title', top: 0, left: 0, right: 0 }); //add both of our views to the Viewport so they're rendered and visible Ext.Viewport.add(carousel); Ext.Viewport.add(info); /** * The Pictures store (see app/store/Pictures.js) is set to not load automatically, so we load it * manually now. This loads data from the APOD RSS feed and calls our callback function once it's * loaded. * * All we do here is iterate over all of the data, creating an apodimage Component for each item. * Then we just add those items to the Carousel and set the first item active. */ Ext.getStore('Pictures').load(function(pictures) { var items = []; Ext.each(pictures, function(picture) { if (!picture.get('image')) { return; } items.push({ xtype: 'apodimage', picture: picture }); }); carousel.setItems(items); carousel.setActiveItem(0); }); /** * The final thing is to add a tap listener that is called whenever the user taps on the screen. * We do a quick check to make sure they're not tapping on the carousel indicators (tapping on * those indicators moves you between items so we don't want to override that), then either hide * or show the info Component. * * Note that to hide or show this Component we're adding or removing the apod-title-visible class. * If you look at index.html you'll see the CSS rules style the info bar and also cause it to fade * in and out when you tap. */ Ext.Viewport.element.on('tap', function(e) { if (!e.getTarget('.x-carousel-indicator')) { if (titleVisible) { info.element.removeCls('apod-title-visible'); titleVisible = false; } else { info.element.addCls('apod-title-visible'); titleVisible = true; } } }); }});This is pretty simple stuff and you can probably just follow the comments to see what’s going on. Basically though the app.js is responsible for launching our application, creating the Carousel and info Components, and setting up a couple of convenient event listeners.
We also had a few other files:
Picture Model
Found in app/model/Picture.js, our model is mostly just a list of fields sent back in the RSS feed. There is one that’s somewhat more complicated than the rest though – the ‘image’ field. Ideally, the RSS feed would have sent back the url of the image in a separate field and we could just pull it out like any other, but alas it is embedded inside the main content.
To get around this, we just specify a convert function that grabs the content field, finds the first image url inside of it and pulls it out. To make sure it looks good on any device we also pass it through Sencha IO src, which resizes the image to fit the screen size of whatever device we happen to be viewing it on:
/** * Simple Model that represents an image from NASA's Astronomy Picture Of the Day. The only remarkable * thing about this model is the 'image' field, which uses a regular expression to pull its value out * of the main content of the RSS feed. Ideally the image url would have been presented in its own field * in the RSS response, but as it wasn't we had to use this approach to parse it out */Ext.define('apod.model.Picture', { extend: 'Ext.data.Model', config: { fields: [ 'id', 'title', 'link', 'author', 'content', { name: 'image', type: 'string', convert: function(value, record) { var content = record.get('content'), regex = /img src=\"([a-zA-Z0-9\_\.\/\:]*)\"/, match = content.match(regex), src = match[1];
if (src != "" && !src.match(/\.gif$/)) { src = "http://src.sencha.io/screen.width/" + src; } return src; } } ] }});Pictures Store
Our Store is even simpler than our Model. All it does is load the APOD RSS feed over JSON-P (via Google’s RSS Feed API) and decode the data with a very simple JSON Reader. This automatically pulls down the images and runs them through our Model’s convert function:
/** * Grabs the APOD RSS feed from Google's Feed API, passes the data to our Model to decode */Ext.define('apod.store.Pictures', { extend: 'Ext.data.Store', config: { model: 'apod.model.Picture', proxy: { type: 'jsonp', url: 'https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&q=http://www.acme.com/jef/apod/rss.xml&num=20', reader: { type: 'json', rootProperty: 'responseData.feed.entries' } } }});Tying it all together
Our app.js loads our Model and Store, plus a really simple Picture view that is basically just an Ext.Img. All it does then is render the Carousel and Info Component to the screen and tie up a couple of listeners.
In case you weren’t paying attention before, the info component is just an Ext.Component that we rendered up in app.js as a place to render the title of the image you’re currently looking at. When you swipe between items in the carousel the activeitemchange event is fired, which we listen to near the top of app.js. All our activeitemchange listener does is update the HTML of the info component to the title of the image we just swiped to.
But what about the info component itself? Well at the bottom of app.js we added a tap listener on Ext.Viewport that hides or shows the info Component whenever you tap anywhere on the screen (except if you tap on the Carousel indicator icons). With a little CSS transition loveliness we get a nice fade in/out transition when we tap the screen to reveal the image title. Here’s that tap listener again:
/** * The final thing is to add a tap listener that is called whenever the user taps on the screen. * We do a quick check to make sure they're not tapping on the carousel indicators (tapping on * those indicators moves you between items so we don't want to override that), then either hide * or show the info Component. */Ext.Viewport.element.on('tap', function(e) { if (!e.getTarget('.x-carousel-indicator')) { if (titleVisible) { info.element.removeCls('apod-title-visible'); titleVisible = false; } else { info.element.addCls('apod-title-visible'); titleVisible = true; } }});The End of the Beginning
This was a really simple app that shows how easy it is to put these things together with Sencha Touch 2. Like with most stories though there’s more to come so keep an eye out for parts 2 and 3 of this intergalactic adventure.
Like Android? Help us fix it
February 6, 2012 by Ed Spencer · 4 Comments
Near the end of last week’s Sencha Touch 2 beta release blog post there was an appeal to the community to help raise awareness of a nasty flashing issue with Android 4.x phones. Every time you tried to use an animation on a web page the browser would flash, wait a bit, then finally perform the animation.
We filed a ticket on this about a week ago and thanks to your help (over 300 of you starred the issue), got a prompt response from the Android team with a fix for the flashing issue.
Getting it Right
However, that’s only half the story. While the ugly flash is gone, animation performance on Android 4.x phones is still unacceptable. As it stands a 2 year old device running Android 2.x easily outruns the top of the range devices today running 4.x.
We really want to have excellent support for all Android devices. While 4.x accounts for only 1% of all Android phones today, that number is only going to go up. And when it does, we want to be ready to ship fast, fluid, beautiful apps onto it.
So we’ve created a new ticket with reduced, reproducible test cases and filed it to the bug tracker. We’ll continue to give the Android team as much support as we can in order to resolve this quickly, but once again we’ll need your help.
In fact all we need is a few seconds of your time. Just open the ticket and click the star at the top left. That’s all we need – it tells the Android team just how many people care about this issue and will help them prioritize it accordingly.
If you want to help out more, take a moment to add a comment to the ticket outlining your own experiences with this issue, like the m.lanyrd.com developer did. Highlighting specific cases where you’ve had problems will really help.
Thanks!
Helping raise awareness of this issue will help everyone who uses or develops for Android devices on the web, and enables technologies like Sencha Touch to deliver slick, immersive apps without resorting to rewriting your app for each platform. We appreciate your help!
Sencha Touch 2 Hits Beta
February 1, 2012 by Ed Spencer · 2 Comments
Earlier today we released Sencha Touch 2 Beta 1 – check out the official sencha.com blog post and release notes to find out all of the awesome stuff packed into this release.
This is a really important release for us – Sencha Touch 2 is another huge leap forward for the mobile web and hitting beta is a massive milestone for everyone involved with the project. From a personal standpoint, working on this release with the amazing Touch team has been immensely gratifying and I hope the end result more than meets your expectations of what the mobile web can do.
While you should check out the official blog post and release notes to find out the large scale changes, there are a number of things I’d really like to highlight today.
A Note on Builds
Before we get into the meat of B1 itself, first a quick note that we’ve updated the set of builds that we generate with the release. Previously there had been some confusion around which build you should be using in which circumstances so we’ve tried to simplify that.
Most people, most of the time should be using the new sencha-touch-debug.js while developing their app as it is unminified code that contains all of the debug warnings and comments. If you’re migrating from 1.x, use the new builds/sencha-touch-all-compat.js build as it provides an easier migration path by logging additional warnings when you use 1.x-style class configurations.
Because we provide 5 builds in total we created a guide on the shipped builds and JSBuilder (the tool that creates a custom build specifically for your app). The guide contains a table showing all of the options enabled for each build – hopefully that makes it easy to choose which build is best for your needs.
Performance
In case you haven’t seen Sencha Touch 2 yet the first thing you need to know is that it’s fast. Crazy fast. Check out this side by side comparison between 1.x and 2.x:
Layout performance is enormously faster in 2.x due to a brand new layout engine that operates much closer to the browser’s optimized CSS layout engine. The difference is pretty startling, especially on Android devices, which had sometimes struggled with Sencha Touch 1. Performance remains a top priority for us and we’re really pleased with the improvements that we’ve secured with 2.0.
Navigation View
The new Navigation View is one of the slickest, sexiest things we’ve created for 2.0. I could play with this thing all day. If you’ve got a phone in your pocket or a tablet near by open up the Navigation View example and see it for yourself. If you’re not, check out this beautiful video of it in action:
Navigation Views are really easy to put together and make your application immediately come to life. Check out the Navigation View docs to see how easy it is to add this to your own applications.
Awesome new examples
As of beta 1 we have 24 examples shipped with the SDK, including no fewer than 6 MVC examples – Kitchen Sink, Jogs with Friends, Twitter, Kiva, Navigation View and GeoCongress.
The Kitchen Sink and Twitter examples also take advantage of Device Profiles, which are a powerful way to customize your app to render customized UI for tablets and phones. Take a look at the Kitchen Sink on your phone and on an iPad to see how it rearranges itself depending on the screen size.
Finally, if you’re seeing Sencha Touch 2 for the first time you may not have seen the new inline examples in the documentation center. This is a brand new thing for Sencha Touch and allows you to edit code live on the documentation page and immediately see the results – give it a go on the Carousel docs.
Ludicrous Amounts of Documentation
Speaking of docs, we have a stunning amount of learning material for Sencha Touch 2. We’ve been through all of the major classes, making sure that the functions are clearly documented and that each one has some great intro text that describes what the class does and how it fits in with the rest of the framework.
We’ve also created over 20 brand new guides for Sencha Touch 2, covering everything from getting started through to developing using MVC, using Components and creating custom builds for your applications. We’ve put a huge amount of effort into our docs for Sencha Touch 2 and I really hope it pays off for you guys and makes it easier than ever to create great mobile web apps.
Go Build Something
It’s only beta 1 but we’re very happy with the performance, stability, API and documentation of Sencha Touch 2. I think it’s the best thing we’ve ever created, and really highlights what the mobile web is capable of. 2012 looks set to be a very exciting year for Sencha Touch so I hope you’ll join us on the adventure and build something amazing with it.
The Class System in Sencha Touch 2 – What you need to know
January 28, 2012 by Ed Spencer · 2 Comments
Sencha Touch 1 used the class system from Ext JS 3, which provides a simple but powerful inheritance system that makes it easier to write big complex things like applications and frameworks.
With Sencha Touch 2 we’ve taken Ext JS 4’s much more advanced class system and used it to create a leaner, cleaner and more beautiful framework. This post takes you through what has changed and how to use it to improve your apps.
Syntax
The first thing you’ll notice when comparing code from 1.x and 2.x is that the class syntax is different. Back in 1.x we would define a class like this:
MyApp.CustomPanel = Ext.extend(Ext.Panel, {
html: 'Some html'
});
This would create a subclass of Ext.Panel called MyApp.CustomPanel, setting the html configuration to ‘Some html’. Any time we create a new instance of our subclass (by calling new MyApp.CustomPanel()), we’ll now get a slightly customized Ext.Panel instance.
Now let’s see how the same class is defined in Sencha Touch 2:
Ext.define('MyApp.CustomPanel', {
extend: 'Ext.Panel',
config: {
html: 'Some html'
}
});
There are a few changes here, let’s go through them one by one. Firstly and most obviously we’ve swapped out Ext.extend for Ext.define. Ext.define operates using strings – notice that both ‘MyApp.CustomPanel’ and ‘Ext.Panel’ are now wrapped in quotes. This enables one of the most powerful parts of the new class system – dynamic loading.
I actually talked about this in a post about Ext JS 4 last year so if you’re not familiar you should check out the post, but in a nutshell Sencha Touch 2 will automatically ensure that the class you’re extending (Ext.Panel) is loaded on the page, fetching it from your server if necessary. This makes development easier and enables you to create custom builds that only contain the class your app actually uses.
The second notable change is that we’re using a ‘config’ block now. Configs are a special thing in Sencha Touch 2 – they are properties of a class that can be retrieved and updated at any time, and provide extremely useful hook functions that enable you to run any custom logic you like whenever one of them is changed.
Whenever you want to customize any of the configurations of a subclass in Sencha Touch 2, just place them in the config block and the framework takes care of the rest, as we’ll see in a moment.
Consistency
The biggest improvement that comes from the config system is consistency. Let’s take our MyApp.CustomPanel class above and create an instance of it:
var myPanel = Ext.create('MyApp.CustomPanel');
Every configuration has an automatically generated getter and setter function, which we can use like this:
myPanel.setHtml('New HTML');
myPanel.getHtml(); //returns 'New HTML'
This might not seem much, but the convention applies to every single configuration in the entire framework. This eliminates the guesswork from the API – if you know the config name, you know how to get it and update it. Contrast this with Sencha Touch 1 where retrieving the html config meant finding some property on the instance, and updating it meant calling myPanel.update(’New HTML’), which is nowhere near as predictable.
Instantiating
You probably noticed that we used a new function above – Ext.create. This is very similar to just calling ‘new MyApp.CustomPanel()’, with the exception that Ext.create uses the dynamic loading system to automatically load the class you are trying to instantiate if it is not already on the page. This can make life much easier when developing your app as you don’t have to immediately manage dependencies – it just works.
In the example above we just instantiated a default MyApp.CustomPanel but of course we can customize it at instantiation time by passing configs into Ext.create:
var myPanel = Ext.create('MyApp.CustomPanel', {
html: 'Some Custom HTML'
});
We can still call getHtml() and setHtml() to retrieve and update our html config at any time.
Subclassing and Custom Configs
We created a simple subclass above that provided a new default value for Ext.Panel’s html config. However, we can also add our own configs to our subclasses:
Ext.define('MyApp.CustomPanel', {
extend: 'Ext.Panel',
config: {
html: 'Some html',
anotherConfig: 'default value'
}
});
The ‘anotherConfig’ configuration doesn’t exist on Ext.Panel so it’s defined for the first time on MyApp.CustomPanel. This automatically creates our getter and setter functions for us:
var myPanel = Ext.create('MyApp.CustomPanel');
myPanel.setAnotherConfig('Something else');
myPanel.getAnotherConfig(); //now returns 'Something else'
Notice how the getter and setter names were automatically capitalized to use camelCase like all of the other functions in the framework. This was done automatically, but Sencha Touch 2 does another couple of very nice things for you – it creates hook functions:
Ext.define('MyApp.CustomPanel', {
extend: 'Ext.Panel',
config: {
html: 'Some html',
anotherConfig: 'default value'
},
applyAnotherConfig: function(value) {
return "[TEST] " + value;
},
updateAnotherConfig: function(value, oldValue) {
this.setHtml("HTML is now " + value);
}
});
We’ve added two new functions to our class – applyAnotherConfig and updateAnotherConfig – these are both called when we call setAnotherConfig. The first one that is called is applyAnotherConfig. This is passed the value of the configuration (’default value’ by default in this case) and is given the opportunity to modify it. In this case we’re prepending “[TEST] ” to whatever anotherConfig is set to:
var myPanel = Ext.create('MyApp.CustomPanel');
myPanel.setAnotherConfig('Something else');
myPanel.getAnotherConfig(); //now returns '[TEST] Something else'
The second function, updateAnotherConfig, is called after applyAnotherConfig has had a chance to modify the value and is usually used to effect some other change – whether it’s updating the DOM, sending an AJAX request, or setting another config as we do here.
When we run the code above, as well as ‘[TEST] ‘ being prepended to our anotherConfig configuration, we’re calling this.setHtml to update the html configuration too. There’s no limit to what you can do inside these hook functions, just remember the rule – the apply functions are used to transform new values before they are saved, the update functions are used to perform the actual side-effects of changing the value (e.g. updating the DOM or configuring other classes).
How we use it
The example above is a little contrived to show the point – let’s look at a real example from Sencha Touch 2’s Ext.Panel class:
applyBodyPadding: function(bodyPadding) {
if (bodyPadding === true) {
bodyPadding = 5;
}
bodyPadding = Ext.dom.Element.unitizeBox(bodyPadding);
return bodyPadding;
},
updateBodyPadding: function(newBodyPadding) {
this.element.setStyle('padding', newBodyPadding);
}
Here we see the apply and update functions for the bodyPadding config. Notice that in the applyBodyPadding function we set a default and use the framework’s unitizeBox function to parse CSS padding strings (like ‘5px 5px 10px 15px’) into top, left, bottom and right paddings, which we then return as the transformed value.
The updateBodyPadding then takes this modified value and performs the actual updates – in this case setting the padding style on the Panel’s element based on the new configuration. You can see similar usage in almost any component class in the framework.
Find out more
This is just a look through the most important aspects of the new class system and how they impact you when writing apps in Sencha Touch 2. To find out more about the class system we recommend taking a look at the Class System guide and if you have any questions the forums are a great place to start.
Sencha Touch 2 PR4 – Big Improvements in Data and MVC
January 24, 2012 by Ed Spencer · 2 Comments
Today we released Sencha Touch 2.0 PR4 – the fourth and final preview release before we hit beta. While we’re technically calling this one a preview release, we’re pretty happy with the performance, stability and overall quality of this release and consider it exceptionally close to beta quality.
As well as a good number of enhancements and bug fixes PR4 brings a couple of long-awaited improvements to two of the most important parts of Sencha Touch – the data package and the application architecture.
First up, the data package has been ported to use the new config system, which normalizes all of the configuration options for every class in the data package, providing a clean and predictable way to configure and update your data classes. We’re still cleaning up some of the data package documentation and given the scope of some of the changes we’re expecting a few bugs to appear as a result but overall we’re very happy with the improved capabilities of Ext.data.
MVC Improvements
The second big improvement in PR4 is to the application architecture. The MVC classes have also been upgraded to use the new config system, again yielding big improvements in the API and general flexibility of your code.
History support has been baked directly into Controllers, enabling you to easily define routes that your Controller cares about, as well as the functions that handle those routes right there in your Controller file. The Kitchen Sink example has been upgraded to use routes out of the box – try it on a mobile device or desktop browser and watch how it reacts to the back/forward buttons.
Equally important, Device Profiles have been upgraded to make creating apps that adapt to different screen sizes much simpler than ever before. Once again the Kitchen Sink has been upgraded to take advantage of device profiles. If you load it on a tablet device you’ll see a split screen view with the menu on the left and the content on the right, whereas the phone version employs a nested list to save screen space.
To cap it off the deep linking support means you can navigate to any view on a phone, send the link to a friend on a tablet and they’ll be taken to the same view customized for their screen size. As an example, try opening http://dev.sencha.com/deploy/sencha-touch-2-pr4/examples/kitchensink/#demo/forms on a tablet and a phone to see it show the Forms demo specialized for each type of device.
As PR4 is the first time we’ve exposed this expanded functionality to the public we expect that there will be bugs and edge cases that crop up. We’ll be keeping a close eye on the bug forums and addressing any issues as quickly as possible, as well as creating additional MVC-driven examples for you to learn from. For now, the kitchen sink is the best example of Sencha Touch 2 MVC in action.
Docs
We’ve made a huge push over the last couple of years to radically improve our documentation, and I think that even in the pre-beta PR4 release Sencha Touch 2 has the best docs we’ve ever created. While there are still holes to be filled in, we already ship with 20 guides on how to use the framework, including 4 brand new guides for PR4:
As well as the guides, most of the classes now contain generous documentation explaining their function and the context in which they operate. As we move to beta and then to GA we’ll be shifting our focus onto producing great demos and examples to showcase the framework’s capabilities and provide realistic sample code to draw from.
There’s a full set of release notes explaining the improvements in PR4 and the important known issues. We expect to be shipping regular releases from now until GA so be sure to keep an eye on the forums, twitter and the sencha blog for more details.
