Tyson Lloyd Cadenhead – UI / UX Developer

Javascript Variables Accessibility

August 4, 2010

When I started writing JavaScript (and code in general, for that matter), one of toughest things for me to wrap my head around was what variables and functions I could access from where. For example, I would try things like this:

alert(MyVariable);
var MyVariable = ‘This is a variable!’;

The previous code would fail because the variable hadn’t been set yet when it was called. Instead, it should look more like this:

var MyVariable = ‘This is a variable!’;
alert(MyVariable);

The previous code will work because the variable had been set before it was called. You see, JavaScript is a linear language. Even files have to be loaded in a linear fashion to guarantee that you aren’t calling any variables that are not already set. That’s why if you’re using jQuery, you have to load it into the DOM before you load any scripts that use the jQuery library. I know that’s pretty basic, but it’s the starting point for the rest of this.

How about this example?

function MyFunction(){

var myVariable = ‘Test’;

}
MyFunction();
alert(myVariable);

That example will also fail because the variable is created inside the function and the variable is being called outside of it. There are a few of ways to access variables that are set inside of functions, however. The code below will work because the variable is already defined outside of the function. The variable is updated inside the function, but it is updated before we alert it and so it is still accessible.

var myVariable;
function MyFunction(){
myVariable = ‘Test’;

}

MyFunction();
alert(myVariable);

Another way to retrieve variables set inside a function is to return them.

function MyFunction(){

var myVariable = ‘Test’;
return myVariable;

}

var myVar = MyFunction();
alert(myVar);

The code above will work because the function doesn’t rely on any global variables and it simply returns the variable that is set inside of it. In this case, you could literally say that MyFunction equals ‘Test.’ You can also return the variable using the ‘this’ associated with the function:

function MyFunction(){

this.myVariable = ‘Test’;

}

var myVar = MyFunction().myVariable;
alert(myVar);

When trying to figure out if a variable will be accessible, ask yourself if it is on the same level (not nested in a function) as the place you are attempting to call the variable or if it is a parent (a function or more higher than the variable you are attempting to call.) If the answer is yes, then you will be able to get to the variable. That’s why something like this won’t work:

function MyFirstFunction(){

var myVariable = ‘Test’;

}

function MySecondFunction(){

alert(myVariable);

}

MyFirstFunction();
MySecondFunction();

But this will:

var myVariable;
function MyFirstFunction(){

myVariable = ‘Test’;

}

function MySecondFunction(){

alert(myVariable);

}

MyFirstFunction();
MySecondFunction();

Any questions?

Sencha Application Event Listening

July 17, 2010

If you’re like me, you are constantly looking for better ways to architect your JavaScript applications to be scalable and modular.  One of the keys to writing an application that fits the bill is to use reusable components that, instead of calling other functions or components directly, broadcast events that multiple components may be listening for.  I’ve been on a hunt to figure out how to do this correctly for a while now and I’ve finally come upon a few good solutions.

For those of you who don’t know, Sencha (formerly known as EXT) is a JavaScript library that provides tons of tools for Rich Internet Application development.  If you are curious about what it can do, check out some examples.  If you are writing a Sencha application, a big part of the job is already done for you.  In this post, I will assume that you already have a basic knowledge of EXT / Sencha and that you know how to get it up and running.

First of all, you need an application component.  This is the main component that all of the other components live inside.  It doesn’t matter what kind of component it is as long as it is a valid EXT component that can contain other EXT components.  For example:

var application;
myApplication = Ext.extend(Ext.Panel, {

height: 500,
width: 700,
initComponent: function() {

this.addEvents (‘myCustomEvent’);
this.items = [

new myButton({ application: this }),
new myContainer({ application: this })

];
myApplication.superclass.initComponent.call(this);

}

});

application = new myApplication();
application.render(document.body);

Some things to make note of are that the Application is extending the EXT Panel. When the component is initialized, a function is being called that uses the component as the “this.” We added an event called “myCustomEvent” that we will now be able to listen to and fire. Also, we initialized a component called “myButton” and a component called “myContainer” and passed the application into them. Shall we proceed?

Next, we need to create the “myButton” component. Don’t forget to include this above the application in your code, or the “myApplication” component won’t know where to find “myButton.”

myButton = Ext.extend(Ext.Button, {

text: ‘Click me’,
initComponent: function() {

var application = this.application;
this.handler = function(e){

var myVariable = ‘This is a variable’;
application.fireEvent(‘myCustomEvent’, myVariable);

}
myButton.superclass.initComponent.call(this);

}

});

What’s happening here is that we are creating a button that fires a “myCustomEvent” event when it is clicked and passes a variable that we just made up. You can pass as many variables as you need to here, and they will typically be more useful than a string that says “this is a variable.” It’s just an example, silly.

Last of all, we need to make an event listener that will “hear” the “myCustomEvent” being announced and will act upon it. The great thing about building an application this way is that it won’t break if there ceases to be a component listening for your event, or if the event ceases to be announced. The application simply handles sending and receiving events. So, our listener will look something like this:

myContainer = Ext.extend(Ext.Container, {

text: ‘Some text’,
initComponent: function() {

var component = this;
this.application.addListener(‘myCustomEvent’, function(myVariable){

alert(myVariable);

}
myContainer.superclass.initComponent.call(this);

}

});

This adds an event listener that fires when the “myCustomEvent” is fired and alerts us with the variable. You can also use the “component” variable that we created to modify the myContainer component based on the event variables. When put together, our code looks something like this:

var application;

myContainer = Ext.extend(Ext.Container, {

text: ‘Some text’,
initComponent: function() {

var component = this;
this.application.addListener(‘myCustomEvent’, function(myVariable){

alert(myVariable);

}
myContainer.superclass.initComponent.call(this);

}

});

myButton = Ext.extend(Ext.Button, {

text: ‘Click me’,
initComponent: function() {

var application = this.application;
this.handler = function(e){

var myVariable = ‘This is a variable’;
application.fireEvent(‘myCustomEvent’, myVariable);

}
myButton.superclass.initComponent.call(this);

}

});

myApplication = Ext.extend(Ext.Panel, {

height: 500,
width: 700,
initComponent: function() {

this.addEvents (‘myCustomEvent’);
this.items = [

new myButton({ application: this }),
new myContainer({ application: this })

];
myApplication.superclass.initComponent.call(this);

}

});

application = new myApplication();
application.render(document.body);

Should I use a JS Framework?

June 12, 2010

There are literally tons of JavaScript frameworks out there to ease the pain of website and application development.  Obviously, the most popular one out there right now is jQuery, but that is not to say that there are not other libraries out there.  So the question becomes, should developers use libraries or is it just a crutch that keeps them from learning real JavaScript?  Here are some thoughts on the subject.

  • I think that everyone should start out learning the basics of JavaScript before learning a library.  When you see some of the things that you can do with jQuery or YUI or Prototype, you’ll probably want to jump right into the framework, but here are some benefits of learning JavaScript proper to begin with:
    • When you know the basics of JavaScript such as how to loop over an array, how to write a conditional statement and how to manipulate the DOM, you’ll have a better understanding of what the library your using is doing.  Contrary to popular opinion, jQuery is not magic, and it does not do anything that you couldn’t do with plain JavaScript, it just makes it easier to do things that would previously have taken more code by running the variables you give it through functions.
    • When you know the basics, you will be able to tell when something is easier to do without the library and when the library is helpful.  You won’t have to trust that it’s necessarily better just because it’s a library method.  It may not be.
    • Libraries have limitations.  There are things that you can do with plain JavaScript that you can’t do with a library.  No JavaScript library was built to be a replacement for JavaScript, they were all written to be an addition to it.
  • Once you know the basics of JavaScript, using a framework or library will help you to write less code and do more with it.  Specifically with jQuery, manipulating the DOM, applying listeners and events and performing AJAX requests requires significantly less code.
  • Frameworks and libraries extend functions that somebody else wrote, so you don’t have to.  Let’s just face it, John Resig and the jQuery team could probably write loops around you with their code.  They are good at what they do.  The best part is that they already did it, so you don’t have to.  You can focus on other things!
  • Don’t get too attached.  If you can, try to abstract the way you interact with your framework in case you ever need to switch frameworks or the framework you use stops being supported.  These things happen.  I’ve been trying to find an article abstracting JavaScript frameworks to point you to, but I haven’t found one yet.  Perhaps I will have to write one.

These are my thoughts on the subject.  Can you think of any arguments for or against using JavaScript frameworks?

See More