What is a Store? How does it work? Más videos
Descripción del tema
Resources
For this tutorial, the resources are a HTML and a JS file where we'll be working, so go ahead and download it and copy them inside of the folder "ajax" that we've created in the previous tutorial, this folder is inside of the "course" folder in the Web server we installed in the first chapter of this course.Encapsulating the tutorial
Before we start with the first example we need to encapsulate the code we will be writing to avoid future issues.//the namespace for this tutorial Ext.ns('com.quizzpot.tutorial'); com.quizzpot.tutorial.Store = { //dummy information will go here init: function(){ //this will be executed when the DOM is ready to be used //create the store here //load the information in the store here //create the “listeners” of the buttons here } //create the method "orderAsc" here //create the method "orderDesc" here //create the method "filter" here //create the method "query" here //create the method"count" here //create the method"find" here //create the method"log" here } //execute the function "init" when the DOM is ready to be used Ext.onReady(com.quizzpot.tutorial.Store.init,com.quizzpot.tutorial.Store);I have commented the place where we're going to write the code for this tutorial, so you can have a better idea of the final structure of the code.
The information
For this example we're going to get the information from an array, it's important to recall that we must create a two dimensional array which is going to be "processed" by the store we're going to create later on, this array will be at the beginning of the object "com.quizzpot.tutorial.Store" like this:data: [ //dummy information for the example [1,'Crysfel','Software developer','m',25], [2,'Sasha','Figure skater','f',23], [3,'Jack','Software Architect','m',35], [4,'John','Javascript developer','m',24], [5,'Sara','Tester','f',31] ],The information is inside of an array which also has other arrays with information, every "inner" array will be a record where the position zero is the "identifier" of the record, the position one is the "name" of a person, position two the "occupation", the position three is the "gender" of the person and the position five is the "age".
Create a Store with local information
We are going to create an "ArrayStore", which is a small helper class to make creating Stores from Array data easier. So create the ArrayStore like this://creating an instance from the SimpleStore this.store = new Ext.data.ArrayStore({ fields: [ //defining the fields... {name:'name',mapping:1}, {name:'occupation',mapping:2}, {name:'gender',mapping:3}, {name:'age',mapping:4} ], id: 0 //defining the Id's position for every record });We have created the store but it doesn't have information yet even though is capable of reading the array we previously defined; the property "fields", which is defined in the configuration of the store, is where we define the name of the properties of the records and we can see it's related to the array with the property "mapping", in this case we assign the position in the array where we're going to get the content to the property mapping.
Loading the information to the Store
Enter the information in the Store is very easy because we're using the local information saved in an array. We need to load the data to the store in order to use the array we defined.//load the information of the array this.store.loadData(this.data);If everything went well, we can use the information contained in the store.
Create the “listeners” of the buttons
At this moment we're going to create the "listeners" for the event click on every button we have in the HTML document.Ext.fly('personBtn').on('click',this.find,this); Ext.fly('txt').on('keyup',function(event,cmd){ if(event.getKey() === event.ENTER){ //when the key is ENTER this.find(); //we will make a search } },this); Ext.fly('ascBtn').on('click',this.orderAsc,this); Ext.fly('descBtn').on('click',this.orderDesc,this); Ext.fly('older2030Btn').on('click',this.query,this); Ext.fly('older30Btn').on('click',this.filter,this); Ext.fly('countBtn').on('click',this.count,this);You can see that the previous code looks familiar and it's because we have talked about the events on elements in previous tutorials, if you don't quite understand the code I recommend you to take a look at the tutorialHandling events on DOM elements and components. You can notice that we haven't assign what's going to happen on each event, we'll do that later on.
Sorting the records
Sorting information is very important and we can do it easily by using the method "sort"., //note: don't forget the comma to separate the methods XD orderAsc: function(){ this.store.sort('name','ASC'); // sort upward this.store.each(function(record){//for every record... this.log(record.get('name')); //print the property "name" },this); this.log('___________________________________'); }, // <--- don't forget to write this comma orderDesc: function(){ this.store.sort('name','DESC'); //sort downward this.store.each(function(record){ //for every record... this.log(record.get('name')); //print the property "name" },this); this.log('___________________________________'); }The method "sort" receives as first parameter the name of the field to sort by and as second parameter the sort order, "ASC" or "DESC"; after we have sorted the records we can loop through the records by using the method "each". The method "log" has not been defined yet, we'll do it later, for now we can have a "console.debug" to print the values in the Firebug console.
Filter the records in the store
Sometimes is necessary to filter information contained in the Store depending on a given criteria, in this example I'm going to create a filter of the people who are older than 30 years-old and I will do it using the method "filterBy"., // <--- don't forget to write the comma filter: function(){ //filter people this.store.filterBy(function(record,id){ return record.get('age') >= 30; //older than 30 years-old }); //for every record this.store.each(function(record){ //print in the "log" this.log(record.get('name')+' is older than 30 '+(record.get('gender')=='f'?'she':'he')+' is '+record.get('age')); },this); //clear the filters this.store.clearFilter(); this.log('___________________________________'); }The method "filterBy" accepts as first parameter a function that will be executed for every record in the store, there's where we've defined the filter (age older than 30 years old), when the function returns "true" the record will be taken and if it returns "false" the record will be discarded. After applying the filter to the store the function "each" is executed, it's important to remember that the function "each" will only be executed on the records that have been filtered previously. With the function "clearFilter" the filters applied to the store are cleared, allowing us to use all the records again.
Search records
The previous method searches for records discarding the records we don't need. The method "queryBy" does something similar but the difference is that it returns the records found in a collection, this can be more useful or easy to understand than the previous method we created.,//<--- don't forget the comma xD query: function(){ //search people who are older than 20 and younger than 30 var collection = this.store.queryBy(function(record,id){ return record.get('age') >20 && record.get('age')<30; }); //for every item in the collection collection.each(function(item,index){ //print the name and age this.log(item.get('name')+' is '+item.get('age')+ ' and '+(item.get('gender')=='f'?'she':'he')+' is younger than 30'); },this); this.log('___________________________________'); }As you can see, this method is very similar to the method we used in the previous example, the only difference is that it returns a collection with the records that meet the specified condition.
Search by property
If we want to search for a single record we can use the method "find" which receives as first parameter the property we will use to make the search, as second parameter receives a "String" or a regular expression with the query criteria, the third parameter is optional and is the index to start searching at, the fourth parameter is also optional and we define if the search will be executed in any part of the text and in the last parameter we define if we want the uppercase or lowercase letters to be ignored.//propiedad: name //value: Crys //comienza en: 0 //To match any part of the string, not just the beginning //no case sensitive comparison this.store.find('name', 'Crys',0,true,false);The method "find" returns the index of the first matching record in this store specified by the property "name", if nothing is found it returns a "-1".
, //<--- find: function(){ //we get what was introduced in the input text var value = Ext.fly('txt').getValue(); //if nothing was entered, exit this function if(Ext.isEmpty(value)) return; //search by the property "name" var index = this.store.find('name',value,0,true,false); //if something's found if(index>=0){ //take the record with the index... var record = this.store.getAt(index); //and print the information found this.log(record.get('name')+' work as a '+record.get('occupation')+' and '+(record.get('gender')=='f'?'she':'he')+' is '+record.get('age')+' years old'); }else{ //if nothing's found, notify the user this.log('<strong>'+value+' not found!</strong>'); } }Notice we have used the method "getAt" to get the full record by passing the index. If we already know the record ID we can retrieve it by using the method "getById". In the next example we're going to check if the user has entered a number in the input text and we will use it as the ID, if text was entered then we will run the previous code.
, //<--- find: function(){ //get what was entered in the input text var value = Ext.fly('txt').getValue(); //if nothing was entered, exit this function if(Ext.isEmpty(value)) return; //if the value is numeric if(/^\d+$/.test(value)){ //search by ID var record = this.store.getById(value); if(!Ext.isEmpty(record)){ //if something was found, print the info this.log(record.get('name')+' work as a '+record.get('occupation')+' and '+(record.get('gender')=='f'?'she':'he')+' is '+record.get('age')+' years old'); }else{ //if nothing was found, notify the user this.log('<strong>Record with id: '+value+' was not found!</strong>'); } }else{ //search by the property "name" var index = this.store.find('name',value,0,true,false); //if something was found if(index>=0){ //get the record by the index... var record = this.store.getAt(index); //and print the information found this.log(record.get('name')+' work as a '+record.get('occupation')+' and '+(record.get('gender')=='f'?'she':'he')+' is '+record.get('age')+' years old'); }else{ //if nothing was found, notify the user this.log('<strong>'+value+' not found!</strong>'); } } }The previous code performs the search by ID or by the property specified (in this case "name").
Count the records of the store
To count the records that are currently in the store is very simple, we only need to use the method "getCount"., //<--- count: function(){ //print the total number of records this.log('<strong>Total records: '+this.store.getCount()+'</strong>'); }Notice that this method only returns the records that are currently in the store.
The Log
The last thing we're going to do is define the method "log" we have been using to display the messages., //<--- log: function(txt){ var el = Ext.get('response'); // get the LOG el.select('p.newest').removeClass('newest'); // remove the last update Ext.DomHelper.append(el,'<p class="newest">'+txt+'</p>'); //update the log el.scrollTo('top',el.dom.scrollHeight); //scroll down el.select('p.newest').highlight('F5FC49',{duration:0.5}); //highlight the last message }In the previous code we got the node "response" and we added the text we received in the parameter "txt", after that we highlighted the new text in yellow.
Conclusions
Is important to know how to search information in a store because this component is used to manipulate information and will help us understand more the Framework. In this tutorial we created a simple store that gets the information from an array we defined with JavaScript, in the "real world" the information will come from a database, a Web service or some other place, in the following tutorials we will learn how to do that. If you have any questions or suggestions, please leave a comment and I will answer as fast as I can. Also don't forget to follow our updates in Twitter or subscribe to the feeds.Te gustaría recibir más tutoriales como este en tu correo?
Este tutorial pertenece al curso Learning Ext JS 3, te recomiendo revises el resto de los tutoriales ya que están en secuencia de menor a mayor complejidad.
Si deseas recibir más tutoriales como este en tu correo te recomiendo registrarte al curso, si ya eres miembro solo identifícate y registrate al curso, si no eres miembro te puedes registrar gratuitamente!
Si no gustas registrarte en este momento no es necesario! Aún así puedes recibir los nuevos tutoriales en tu correo! Jamás te enviaremos Spam y puedes cancelar tu suscripción en cualquier momento.
Regístrate a este curso
Este tutorial pertenece al curso Learning Ext JS 3, revisa todos los tutoriales que tenemos en este mismo curso ya que están en secuencia y van de lo más sencillo a lo más complicado.
Tendrás acceso a descargar los videos, códigos y material adicional.
Podrás resolver los ejercicios incluidos en el curso así como los Quizzes.
Llevarás un registro de tu avance.
Se el primero en comentar!