Learning Ext JS 3

Status bar in panels and windows Más videos

Descripción del tema

A status bar is useful to inform the user what is happening in the application. This component was removed from the new version of ExtJS (version 3.0) and the argument of this decision is that this component was the same as the Toolbar and the component doesn't have to be in the Framework anymore. In this tutorial I will show you how we can recreate a status bar with Ext 3.0.

Resources

Before you start this tutorial you need to download the resources, unzip them and copy them in the Web server we installed at the beginning of this course. The example we're going to do is add a status bar to a window, on the right side it will have a clock, also the window will have a text area where the user can write and meanwhile in the status bar the application is going to show the number of words typed, once the user has stopped typing a message saying "saving" will be displayed. We're not going to save the text the user has entered because our goal is to learn how to use the status bar, you can see the demo of the example.
statusbar image

Demostration

Packaging the tutorial

The first thing we need to do is package the code we're going to write for this tutorial.
Ext.ns('com.quizzpot.tutorial'); 

com.quizzpot.tutorial.StatusbarTutorial = { 
	init: function(){
		//the code goes here
	}
}

Ext.onReady(com.quizzpot.tutorial.StatusbarTutorial.init,com.quizzpot.tutorial.StatusbarTutorial);

Creating the status bar

To create the status bar we need to create an instance of the component "Ext.Toolbar" and we will assign it to the component Window by using the property "bbar".
//creates the status bar
var statusbar = new Ext.Toolbar({ 
	items:['Ready!'] 
}); 
		 
this.win = new Ext.Window({ 
	title: 'Word Processor - Quizzpot', 
	width: 600, 
	height: 450, 
	bbar: statusbar, // <--- add the status bar to the window
	bodyStyle:'background-color:#fff', 
	items: [{ 
		xtype: 'textarea', 
		id: 'word-textarea', 
		style: 'width:100%;height:100%;border:none;', 
		enableKeyEvents: true 
	}] 
}); 
		 
this.win.show();
The previous code creates a toolbar that has only one text (Ready!), after that it creates a window (inherited from Ext.Panel) and assigns the status bar to this window using the property "bbar", the window has another element, which is the text area where the user is going to write, later on we will add the events so don't worry about them right now. At this moment we should see in our browser something like this:
statusbar image

A simple status bar

Text in the Statusbar

What we're going to do right now is create the containers of the text we're going to use.
//method vars 
var status = new Ext.Toolbar.TextItem({id:'status',text:'Ready!'}); 
var clock = new Ext.Toolbar.TextItem({id:'clock',text: '00:00:00 AM'}); 
// instance var 
this.words = new Ext.Toolbar.TextItem({id:'words',text:'0 words'}); 
		 
var statusbar = new Ext.Toolbar({ 
	items:[status,'->',this.words,'-',clock] 
});
The previous code creates three "TextItems", these are the text containers that can be inserted into a toolbar; I'm doing it like this because I need to assign an "id" to each item so I can have access to them later on and be able to modify it's content. One important thing I'd like to point out is that the variables "status" and "clock" are being created as method's variables meanwhile the variable "words" is an instance variable because it will be used by another method of the object "StatusbarTutorial" later on ( I haven't defined this method yet). With what we have written so far, we should see a screen like this one:
statusbar image

Component TextItem to display text in a Toolbar

Programming a clock

Let's start programming the clock we're going to show on the right side of the screen. We need to create a task that gets executed every second and modify the text of the "TextItem clock" we've defined previously.
// Start a simple clock task that updates a div once per second 
var updateClock = function(){ 
	Ext.getCmp('clock').setText(new Date().format('g:i:s A')); 
} 

//Configuration object for the task		 
var task = { 
	run: updateClock, //the function to run
   	interval: 1000 //every second 
} 

//creates a new manager 
var runner = new Ext.util.TaskRunner(); 
runner.start(task); //start runing the task every one second
In the previous code we created a function that will be executed continuously, this function updates the text of the clock with the current hour of the system; the following step is to create a configuration object to perform a task where we will define two parameters: "run" which is the parameter where we define the function that is going to be executed and the "interval" parameter which is the time that will be execute continuously, this parameter must be especified in miliseconds; the last step we need to do is create an instance of the component "TaskRunner" and initialize the execution of the desired tasks, in this case we will only executte one task, but we can execute many at the same time.
statusbar image

A clock in the status bar

Word counter

The next step will be updating the word counter when the user is writing, therefor we're going to use the event "keypress" and "blur" in order to update immediately when the user is typing a new word.
Ext.getCmp('word-textarea').on('keypress',this.countWords,this); 
Ext.getCmp('word-textarea').on('blur',this.countWords,this);
With the method "getCmp" we can get the component by its identifier (id) and use it, after that we can add the "listener" to the events I mentioned previously. If you've noticed in the second parameter we are referring an instance method which we haven't defined yet and the third parameter is the "scope" we are assigning. Let's go ahead and define the method that will be in charge or count the words of the text entered by the user, lets define it immediately after the method "init".
, // <-- do not forget the comma between methods
	 
countWords:  function(textarea){ 
              var value = textarea.getValue(); //get the string
              var wc = 0; // word counter
                            
              if(!Ext.isEmpty(value)){ // if there is something in the textfield
		wc = value.match(/\b/g); //find the spaces 
		wc = wc ? wc.length / 2 : 0; //count the words
             } 
		 
	this.words.setText(wc + ' words'); //print the counter on the status bar
}
The previous code takes the text the user has entered and then initializes a word counter to zero, checks if something was introduced and counts the words looking for spaces and calculating the total number of words, at last it updates the status bar with the new value. The following image shows how the word counter suppose to look:
statusbar image

Word counter

Autosave

We are going auto save what the user is writing, we're going to do that by displaying a message saying "Saving draft..." in the status bar and after a second we will show the last time the text was saved; we're not going to save the text in a database on this tutorial since we only want to learn about the status bar, but you can do it if you want to, all you need to do is send the content of the input box to the server using Ajax, when the server responds you can let the user know that the text was saved.
Ext.getCmp('word-textarea').on('keypress', function(textarea){ 
	var text = Ext.getCmp('status'); 
	text.setText('Saving draft...'); 
	(function(){ 
		    text.setText('Draft auto-saved at ' + new Date().format('g:i:s A')); 
	}).defer(2000); 
}, this, {buffer:3000});
We have to write the previous code inside of the function "init" with the "listeners" we added previously; I just want to point out something important, as you can see the function "on" accepts a configuration object in the fourth parameter, in this parameter we're indicating the property "buffer" to delays the function the number of milliseconds defined by us and if the event is fired again within that time the original handler is not invoked, but the new handler is schedule in its place; in other words this fuction will be executed after 3 seconds without the user pressing any key; by doing this we prevent the function to be executed for every letter that the user enters. The information will be saved after an inactivity of three seconds. Another important thing of the previous code is that we are using an anonymous function that is executed after two seconds, I could have used the "setTimeout" function but I wanted to show you how to use the method "defer".
statusbar image

Autosaving the text

Conclusions

Even though in the new version of ExtJS the statur bar no longer exist we can still recreate it, actually the reason why it was removed is because it doesn't make much sense to have a component that perform the same actions as the "Toolbar". The ExtJS community has created a plugin for the "Statusbar" and has very useful methods. If you have any questions or suggestions you can feel free to leave them in the comment's section or you can join the Quizzpot forums and we can all help you answer your questions or problems.

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.

¿Olvidaste tu contraseña?

Se el primero en comentar!

Instructor del curso

Crysfel3

Autor: Crysfel Villa

Software engineer with more than 7 years of experience in web development.

Descarga Código Fuente Ver Demostración

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.