Category Archives: JavaScript

Some useful tips and information about JavaScript.

Mandoo core 2.0 has arrived!

0
Filed under JavaScript, Mandoo, Web Development
Tagged as ,

The Mandoo JavaScript Library team has spent the last months in 2009 to fully rewrite the project core. So, as a New Year’s gift, we’re proud to announce the official 2.0 release! – that is already followed bt 2.01, actually.

What changed:

  • Upgraded Sizzle CSS selector engine to the latest version and compressed it with Google Closure
  • Faster and even more flexible DOM API
  • A more powerful animation engine was introduced, faster, making complex easings/animations easier
  • Effects has been added to a bundled plug-in
  • Modularization engine concept refactored
  • Many bugs were killed and features added

The Mandoo core is now even more extensible, easier than before. Fun fact: the uncompressed core is now 41.5kb (against ~66kb from 1.3x version) – we gained enhancements in all of the aspects.

All the code is at the Github repository, go grab it.

Note: if you find any bug on this new version, please tell us. Also, the new documentation is being written; if you are interested, please fork it and help.

Enjoy – and contribute! :P

jQuery, Prototype, Mandoo – creating DOM elements

0
Filed under JavaScript, Mandoo, Web Development
Tagged as , ,

While I was porting the Lightbox library to a Mandoo module, I saw the way that Prototype handles elements creation and remembered the jQuery "different" – dirty, actually – way. I tweeted about it and got some replies from others JavaScript developers, dirs and gabrielgilini. This post will show the three different ways these libraries offer to create DOM elements trees. First, the jQuery way:

$('#grid').append(
'<tr class="even">' +
	'<td width="250">' +
		'<input type="checkbox" id="check"/>' +
		'<input type="text" id="item"/>' +
	'</td>' +
	'<td>' +
		'<a class="link" href="#" title="delete this item">Delete</a>' +
	'</td>' +
'</tr>'
);

Well, personally I really don’t like to mess HTML code with my JavaScript stuff (I am almost sure that neither you do). Thinking this way, we have another option, with Prototype:

$$('#grid')[0].appendChild(Builder.node('tr', {className:'even'}, [
	Builder.node('td', {width:'250'}, [
		Builder.node('input', {type:'checkbox',id:'check'}),
		Builder.node('input', {type:'type',id:'item'})
	]),
	Builder.node('td', [
		Builder.node('a', {href:'#',title:'delete this item'}, 'Delete')
	])
]));

Better, but we want something cleaner, simpler. What about joining the best ideas? The Mandoo way, using CSS selectors to create elements (why not? :D ):

u('#grid').append('tr.even')
	.append('td[width=250]')
		.add('input#check[type="checkbox"]')
		.add('input#item[type="text"]')
	.up()
	.append('td')
		.add('a.link[href="#"][title="delete this item"]', 'Delete');

Mandoo helps you to keep things simple, organize your code and follow the best JS coding practices. Share your thoughts and happy coding! :)

the utm project, growing

2
Filed under JavaScript, Mandoo
Tagged as

Hello.

These last months, I’ve been working on the utm js library, and I’m glad that the community is growing and some of you readers are contributing to the project.

Next step is finish the new website and write the documentation pages.

Don’t you know the project yet? Check it out on the site or join our channel (#utmjs at irc.mozilla.org) and get involved! You’re all welcome and any help would be very appreciated.

For now, we need some special attention on:

  • new website
  • documentation
  • design projects
  • project management

Hope to see you there. And no, you don’t need to be an expert on JavaScript; I’m sure that anyone can help.

Soon, a new blog only for the project will be available.Technorati Tags:

OOP JavaScript part 1: the constructor-prototype model

3
Filed under JavaScript

How do we handle “classes” with JavaScript?

Some people says that JS is not object-oriented. But yes, it is. The difference between JS and some others OOP languages is that there are not “classes” in JS. There are “constructors” and “prototypes”.

Constructors

Nothing more than simple functions. You can create an instance by simply calling the function with the new keyword before. Now, by default, the function (then called constructor) returns an instance, a new object.

// create the constructor
function MyConstructor() {

}

// create a new instance
var myInstance = new MyConstructor();

Ok. And where are the methods, properties and all those stuff?
Like any other function, we can use arguments and put their values into the instance, that is referenced inside the constructor by the name this. Firstly, the instance is nothing more than a writable object; so you can add anything you want to it.

function Car(color) {
	// now the instance have the property 'color'
	this.color = color;
}

var myCar = new Car('red');

Prototypes

The instances also can inherit a bunch of defined stuff. Here we go, prototyping. Now we can predefine methods that can be used directly from the instance. So, every instance – including the already created ones – will have the stuff defined into their constructor’s prototype.

function Car(color) {
	this.color = color;
}

var myCar = new Car('red');

Car.prototype.changeColor = function (color) {
	this.color = color;
};

// now, myCar.color = 'blue'.
myCar.changeColor('blue');

We can write any object-oriented app with JavaScript, following the constructor-prototype concept; but some people just don’t like this concept. Therefore, they can use some script that “simulates” the classic class syntax. Sometimes it can make our code more organized. It’s not a huge advantage at all, but just coding preferences: nothing that we can’t do with pure prototyping.

utm + Sizzle

0
Filed under JavaScript, Mandoo, Web Development
Tagged as , , , ,

The utm JavaScript library now is going to use the John Resig’s Sizzle.

Sizzle is a lightweight, fast and pure-JavaScript element selector that uses CSS3-based queries.

Somedays ago, while I was talking to John (the creator of Sizzle and jQuery), I decided to join the Sizzle project and integrate it with utm, as other JS libraries out there are joining too.

Why? Weren’t you writing a selector engine for utm?

Yes, I was. But both utm and Sizzle are open source and the Sizzle code is really, really great. So what’s the problem in using and contributing with it, like any other good open source software? =]
We’re not here for a competition, I don’t want to prove that utm is better or not. I’m trying to make two projects grow together.

Ok. So why don’t you use jQuery?

jQuery is an awesome library, but utm has a different focus. Its objetive is not just provide Ajax features or effects, but to provide an Web Application platform – this is exactly what I’m working on.

So, if you want, join the project too and let’s make it all better. =D

What’s JSON?

0
Filed under JavaScript, Web Development
Tagged as ,

Have you ever heard about JSON? I’m almost sure you have.

JSON (JavaScript Object Notation) is an easy to handle and understand data format used everywhere.

As its name says, it’s based on the way that JavaScript can handle objects, like this:

var myCar = {
	color: 'red',
	doors: 5,
	wheels: 4
};

It’s easy to understand, isn’t it? I have a red car, that have five doors and four wheels.

Now imagine some data got from a database in this format. It would look like this:

var users = [
{ name: 'E. Myller', genre: 'male' },
{ name: 'Voziv', genre: 'male' },
{ name: 'K. Hellen', genre: 'female' },
{ name: 'Elomar', genre: 'male' }
];

It’s also easy to understand, right? We have four users: E. Myller, Voziv, K. Hellen and Elomar.

“Ok, uncle eMyller. It’s pretty beautiful and clean. Any other reason that would make me use it from now on?”

Yes. The usage. Now you can, for example, handle that data got from a database as a simple JS object. Take this example, using the previous code:

var user; while (user = users.shift()) {
	alert(user.name);
}

Easy to understand: it loops through the users and shows the name of each of them.

Many languages today have native support for it. At web, it’s even more useful because we can join some JSON data with Ajax requests and get awesome results easily.

Use your creativity and do things quickly and easily with JSON!

How to load external scripts

0
Filed under JavaScript, Web Development
Tagged as , ,

Sometimes we, for some reason, need to load external scripts to be executed in our page. This post might help with some ideas about it.

There are, basically, two ways for loading scripts.

  1. Using a normal HTTP request
  2. Or using Ajax (XMLHttpRequest)

You can use both, depending on your needing. But what are the differences between them?

  1. Using a normal HTTP request, you append scripts from anywhere (cross-domain) which content is loaded only asynchronously.
  2. Using some Ajax, you can load text asynchronously or not, but you can’t get scripts from outside the domain/port you are (not normally, maybe the browser allow it, but not all browsers).

What’s the better? There’s no better. Just like always, it depends on what you are planning to do. So, are you trying to just execute a script? Or are you trying to get it and execute it so other code will be able to run? – It’s all about time. Loading the script sync/asynchronously makes the difference here.

So, if you need the script exaclty now, i mean, if the code must wait for the script, the solution is use sync Ajax. Otherwise, if the code can wait some milisseconds/secods (or it really doesn’t need to wait anything), you can use a normal HTTP request. Okay, but how?

Doing it using pure JavaScirpt is not that fun. It requires some code, and it can be annoying. So, let’s take a library (I’ll use utm here) to do the stuff). Take a look:

// loading the script asynchronously, normal HTTP request
u.append('script[type="text/javascript"][src="myscripts/some.js"]');
// we can add from another domain/port too:
u.append('script[type="text/javascript"][src="http://site.com/js/some.js"]');

The code above will basically simulate a simple script tag on the BODY of your document (yes, the BODY element is the best place to put scripts in. Why?)
In the other hand:

// I'll need a function called "show", that is in another script in my own domain.
var script = u.append('script[type="text/javascript"]');
// the 'true' here says it to do the request synchronously
script.text( u.get('myscripts/some.js', true) );

// now we can proceed. =)
show(...);

Choose which is better for what you need to do. ;)

Take the <script> out of your <head>!

6
Filed under JavaScript, Mandoo, Web Development
Tagged as , ,

Insert <script>s at the top of a page (at <head>, generally) is so 90’s. It’s not correct and may cause you problems. The most reason for it is that the DOM is not yet fully loaded (ready) when the script runs from the <head> element.

Maybe this explain why you get errors when you try to access any element of the <body> from the scripts above (when you’re not doing it through a “load” or “domready” event, of course).

Then you try a JavaScript library like jQuery: it teaches you that you must continue using scripts at the top and you must use the “domready” event to workaround this. Good, things will work, but… it’s really bad:

  1. Your page content will have to wait for all scripts to be loaded and executed to finally be shown. (thanks for the point, Wilfred Nas)
  2. You will aways depend on “load” or “domready” events to make your code work properly.

So, to get rid of these problems, the best way to attach scripts to your page is by adding them to the end of your <body> element:

	...
	<script type="text/javascript" src="path/to/the/script.js"></script>
	<script type="text/javascript" src="path/to/another/script.js"></script>
</body>
</html>

You may find it weird, but it’s completely valid and is also recommended by Yahoo and many other experienced web developers.

Keep in mind that the most important layer of your page is the content, and the user might see it independently of any extra behavior (JavaScript).

Tell your friends about it. :)

Debugging on IEs

3
Filed under JavaScript, Web Development
Tagged as ,

I was – again – in a quest to find a good version of Microsoft’s Internet Explorer 6 for MS Windows Vista. Don’t know how, but I found in a brazilian blog a really nice solution: IETester, from the DebugBar team. It provides us IE5.5, IE6, IE7 and IE8b1 and the already installed IE version. It means, If you have IE8b2 installed on your Windows PC, you can have all the IEs for testing your web project on! And this is one really cool feature of IETester: We don’t need keep restarting the browser to switch the IE version. We just need to open a new tab, selecting the version we want. Nice, uh? We just have some little issues about the application:

  • The content disappear when we resize the application window
  • The Previous/Next buttons are not working properly
  • Focus is not working properly
  • Java applets are not working
  • Flash is not working on IE6 instance.

But I think that if we need IETester to run JavaScript/CSS/Images test, we don’t need to worry about these ‘problems’. It’s a great tool! I highly recommend it for anyone who need to test web projects on various IE versions. And the DebugBar team also offers some really awesome tools for debugging in IE (JS console, DOM inspector, etc). Check it out!

The utm Project

4
Filed under JavaScript, Mandoo, Web Development
Tagged as , ,

Some years ago, I was developing some web sites, and I started to learn JavaScript. For me, it was just a language that do make things blink on the page. No, it wasn’t. To tell the truth, JavaScript is my preferred programming language. It’s incredibly growing, being implemented in more platforms for more technologies (like hardware accelerated 3D games). Then, some time later, I started out to write some JS stuff, just for learning and, also, for personal use. Now I know, it’s funny, nice to work with. I just love it and the fact that I work with what I like: JavaScript.

After some huge steps (hundreds of failures and success), I came up with my own JS tool, the utm (Some time ago called ImpactAjax and Spark). But why another one JS framework? Not just “another one”. I’m planning to build the most useful library seen so far. How? Getting all the best ideas i saw so far plus all my own ideas, join them up, simplify the usage and prepare a great platform for development, all open-source, totally. Something complete, with many options, but that everyone (even beginners or advanced programmers) can easily do what they want.

I want the simplest. I want the most powerful. I want the fastest. In just some kb of compressed stuff. I want to break paradigms, bringing something really new and cool.
But it’s still not done for the real world…

Sounds interesting?
If yes, I’d ask for your help. I’m alone in this project now and I have not enough time to work on it as I’d like to do. So, if you’re interested on the idea and would want to contribute with anything, please feel free to join our little group at ##utmjs on irc.freenode.net or just post a comment here.

What we need for now:

  • Testing
  • Documentation
  • Suggestions / opinions
  • Ideas
  • Or anything you’d like to contribute with

I’d be soooo glad if you join the project! Let’s make utm grow and be usable!

If you wanna see the code, get it from my utm’s git repo or download it from the site.

Thanks in advance!