Sencha Inc. | HTML5 Apps

Blog

Sencha Basics: An Introduction to Data Stores

June 23, 2011 | David Kaneda

The process of building a complex web application has evolved a lot over the past few years, largely thanks to the ever-evolving browser landscape. Many server-side and native application development paradigms — including MVC, layout systems, and data stores — are moving to frontend web technology like JavaScript. This article will take a brief, high-level, look at data stores, and how they can be used to reduce your development time and future-proof your applications.

For demonstration purposes, we will look at the Twitter homepage, which relaunched a few months ago as a single page application. To be clear, Twitter does not use Sencha frameworks — I am simply using their user interface as a study in development process. We could just as easily look at a variety of other single-page applications like Facebook or Grooveshark.

Let’s take a quick look at the Twitter homepage when you’re logged in:

Twitter homepage

Note that any action a user takes on this screen does not load a new web page but rather fires JavaScript and updates the page dynamically. For this example, we will be looking at one interaction in particular: Clicking “Follow” under the “Who To Follow” list.

Sidebar For Twitter to properly and dynamically update when a user clicks “Follow,” a lot of things need to happen, and very quickly. First, the link we just clicked needs to change from “Follow” to “Unfollow” list. We will also need to bump up the user’s follower count, and then add the newly followed user into the “Following” list.

In traditional web page development, if we were using a basic DOM manipulation library such as jQuery, this would be quite a tedious task and involve things like:

  • Figuring out who the user is choosing to follow, probably by traversing up the DOM tree from the follow button.
  • Selecting the follower count ($(’#followercount’)), increasing the number by one, then replacing the text in the element.
  • Pulling the user’s avatar out of the “Who To Follow” row, and adding it to the front of the “Following” list. Additionally, we would have to remove the last avatar in that list so as not to change the layout.

This is not ideal for a few reasons. First, this would all be custom code in the click handler of the Follow button. If we were to add any additional functionality or UI to the application that involved one’s follower list, we would have to remember to come back and update this code, so our app continued to function properly. Additionally, we would have to duplicate the code in reverse to handle links in the app which “Unfollow.” Lastly, we would have to manually optimize this code by caching selectors, where appropriate. Together, all of this means code that is error-prone and difficult to debug.

There’s a Better Way

Now, let’s look at the same example but introduce the concept of a data store. For those who are unfamiliar, a data store is an abstract representation of a collection of records, almost like a database. In this example, our data store will be the user’s “Following” list. Please note that this is pseudo-code, loosely based on the Ext JS API, but it’s concepts can be used anywhere (there is a similar API for Sencha Touch, for example).

var followingStore = Ext.create('Ext.data.Store', {
        model: 'User'
});

Now, we can take that data store and “bind” relevent elements on the page to it. This means they will listen for changes to the data store itself and update themselves, when necessary.

To create the list of avatars that the user is following, for example, we could do something like this:

// Create the following list (pseudo-code)
var followingList = new Ext.DataView({
        store: followingStore,
        tpl: '<tpl for="."><img src="{avatar-url}" /></tpl>',
        collectData: function(){
                var data = this.callParent(arguments);
                return Ext.Array.slice(data, 0, 5);
        }
});

Here, we’ve created a “DataView,” which is a component that loops through items in a data store and creates DOM elements for each one. We pass in our followingStore, give each item a template, and then use the collectData function to make sure we’re always only showing the 6 most recently followed users. This collectData function will automatically fire anytime the followingStore is updated, so we never have to worry about this part of the page being out of sync.

Similarly, we can create the view which shows the numeric count of people the user is following:

// Create the following count display (psuedo-code)
var followingCountCmp = Ext.create('Ext.Component', {
        tpl: 'Following {followCount}'
});
 
followingStore.on('datachange', function() {
        followingCountCmp.update({
                followCount: followingStore.getCount()
        });
});

With this, we’ve created a basic component, followingCountCmp, which uses a template to show some text about how many people the user is following. We then bind a callback to the datachange event on the data store which updates the component. The datachange event will fire whenever a new user is followed or unfollowed, so again, we don’t have to worry about this follower count breaking in the future.

With these components established, our logic for when the user clicks “Follow” is much simpler. Instead of going through and manually updating DOM elements throughout the page, we can simply call something like the following code, and all of the components will update automatically.

followingStore.add(newUserToFollow);

Now, as we begin to develop “Unfollow” buttons and other functionality around a user’s following list, we can be confident that we don’t have to revisit the code we have already written. Ultimately, this creates code that is more future-proof and accessible to new developers working on our project.

There are 15 responses. Add yours.

Martin Kelly

3 years ago

Excellent Post David,

Where could I learn more about the topics in this post?

Thanks

Krishna HK

3 years ago

Excellent,
What is the basic knowledge to be able to understand how to write and understand the code ?
Is it hard to learn ? I am a self learner and familiar with Classic ASP.
Thanks to let me posted my reply.

Cameron

3 years ago

@Krishna, If your unfamiliar with Ext/Sencha Touch, there will likely be a bit of a steep learning curve as you figure out the APIs. It is a very powerful framework and its worth spending time on some of the other blog posts and tutorials (even full code samples) to see how things are done.

sagar

3 years ago

Hi David,
Really liked your post. I am also trying to play around with use of data store to read nested complex XML from REST type of webservice. I have posted this on thread http://www.sencha.com/forum/showthread.php?136324-Reading-complex-XML-using-XMLReader Do yo.u have any suggestions or thoughts on this ?

Thanks..!

Ronny López

3 years ago

Event-driven programming, that is excellent.

One question, though: when data store data is loaded, does it load all the records from the server ? All the ‘following users’ records ?

How do you get only the last 5 following users and the count from the server without loading the entire list of ‘following users’ ?

David Kaneda

3 years ago

@sagar It would appear ok to me, but I’m not the best to debug detailed data questions. I’m sure we’ll have a support guy on that thread soon.

@Ronny We have lots of options available in these classes, just check out the API docs to learn more. I know there are methods/attributes in there for paginating responses etc., though getting a “total count” might require it’s own API end point. This article was meant more of a general introduction to the concept, so it’s really just pseudo code that I’m showing.

Vladimir

3 years ago

Excellent post! Wish there were a whole series of “Sencha Basics” blogs like this one. I think that would help developers who just begin to explore ExtJS quite a bit.

Yves Deboutton

3 years ago

I would like to see these blog-tutorials with non-pseudo code. Actual Ext-JS code would be more useful.

saiprasad mishra

3 years ago

Very nice post about data store thanks for sharing the expert tip keep blogging guys with all these cool features so that it helps us to use more ext js to full power, its a great framework but now it becomes even greater with more sharing of tips and tricks about all those best features underneath

David Kaneda

3 years ago

@Vladimir Thanks! I am considering turningnthis into a series to help change the mindset of traditional web devs.

@Yves There are actually some great real-world data store guides at http://www.sencha.com/learn/

AwesomeBob

3 years ago

They cruised over things like proxies here but what you’re looking for can be found in the examples and the API. Also just a heads up, the data view’s template isn’t using a field for the image’s src attribute, maybe something like this:
‘<tpl for=”.”>{thumbnail}</tpl>’

camelCase

3 years ago

I find this blog entry a little disappointing. There are too many gaps in the pseudo code for the true beginner to bridge over, so in effect the post does little more than allow existing experts to reaffirm their expertise. I also question the structure of the blog entry, in an already excessively brief article, why waste 40% of column inches on a rehash of the general argument for single page applications and the role for a RIA framework?

Edgar

3 years ago

This bit confused me:
followingCountCmp.update({
          followCount: followingStore.getCount()
      });
Will followingCountCmp now have a property ‘followCount’? Also, this template doesn’t have any variables:
tpl: ‘Following ‘
Shouldn’t it be something like the following?
tpl: ‘Following: ${followCount}’

Similarly, should this:
‘<tpl for=”.”>”” /</tpl>’
be this instead?:
‘<tpl for=”.”>${item.url}</tpl>’

David Kaneda Sencha Employee

3 years ago

@camelCase: Sorry to hear. I admit, it was difficult to decide where to abridge the pseudo-code to make it as digestible as possible, but, I disagree that there is no effect to the post and it is purely meant to “reaffirm expertise.” Quite the opposite — this came after speaking at a few “web design”-centric conferences, and realizing that there are many web developers out there who are alien to the idea of single page web apps. This is meant for that audience, hence the “Sencha Basics” in the title. Perhaps we’ll put the next one directly in the our new Learn section and skip the blog, though, as I suspect you’re right in that it’s preaching to the choir a bit.

@AwesomeBob and @Edgar OH NO! I just realized our CMS actually stripped those out (they were in the same format as our templates). The actual code was just as you both described. Will try to resolve ASAP (maybe I’ll just change the format, since it’s pseudo-code anyway).

Edgar

3 years ago

Wow! Thanks for the super quick response!

Comments are Gravatar enabled. Your email address will not be shown.

Commenting is not available in this channel entry.