iPhone 3.0 geolocation with Javascript
30 June 2009 | No Comments | 38 view(s)
I was watching one of the video tutorials from Apple last night about some custom JS available on Safari, only on the iPhone 3.0, that let’s you interact with the phone and obtain data like the current location, etc.
So I built a little page to see how it works. I included Mootools 1.2.3 from Google servers and the Google Maps API. And voilá, with a few lines of code we have a totally functional web based GSP navigation system. A little bit ugly, but functional. Currenlty it only centers the map on the coordinates given by the phone, and also does a reverse geolocation to obtain the address (actually city, state and country). But it could be easily extended to add markers to the map, or even paths to track the movement.
If you have an iPhone (or an iPhone simulator) go to:
http://enekoalonso.com/research/iphone/geolocation.html
The source code:
-
var Navigator = new Class({
-
initialize: function() {
-
-
// Listen for position changes
-
this.watchId = navigator.geolocation.watchPosition(
-
function(position){ this.position(position) }.bind(this),
-
function() {},
-
{ enableHighAccuracy: true, timeout: 1000, maximumAge: 10000 }
-
);
-
this.infoPanel = $('info');
-
-
// Create the Geocoder and the Map
-
this.geocoder = new google.maps.Geocoder();
-
this.map = new google.maps.Map($('map'), {
-
zoom: 12,
-
mapTypeId: google.maps.MapTypeId.ROADMAP
-
});
-
},
-
-
position: function(position) {
-
// Update labels
-
this.infoPanel.getElement('p.date').set('text', position.timestamp);
-
this.infoPanel.getElement('p.coords').set('text', position.coords.latitude + ', ' + position.coords.longitude);
-
this.infoPanel.getElement('p.altitude').set('text', position.coords.altitude);
-
this.infoPanel.getElement('p.heading').set('text', position.coords.heading);
-
this.infoPanel.getElement('p.speed').set('text', position.coords.speed);
-
-
// Center map
-
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
-
this.map.set_center(latLng);
-
-
// Reverse geolocation (get current address)
-
this.geocoder.geocode({'latLng': latLng},
-
function(results, status) {
-
if (google.maps.GeocoderStatus.OK) this.showAddress(results)
-
}.bind(this)
-
);
-
},
-
-
showAddress: function(results) {
-
// console.dir(response);
-
if (results[1]) {
-
this.infoPanel.getElement('p.location').set('text', results[1].formatted_address);
-
}
-
}
-
});
-
-
window.addEvent('load', function() {
-
new Navigator();
-
});
Enjoy.
Sending messages between Javascript objects
23 April 2009 | 2 Comments | 91 view(s)
When applications (or websites) get pretty big, it usually happens that a lot of different objects or classes interact with each other or, even worst, depend on each other to achieve the site functionality.
A simple example could be a Tabs manager class, which controls a set of tabs in the page. Sometimes, the content in this tabs is sensitive to when the tabs are shown or hidden. At this point you have three options: either the Tabs class needs to know about the content or you create a set of callback functions or you use custom events. Still, for every one of these options you are going to need variables referencing the instances of your classes (this is: var myTabs = new Tabs())
Personally, I don’t like having global variables for the objects I create. I think the code gets very messy and complicated.
So, after dealing with all these issues at work day after day I thought it would be very cool to have a messaging system between my classes, the same way other languages like Cocoa do (in a more simpler way, at least for now).
Sending messages between classes
Wouldn’t it be nice if the Tabs class would send a message every time a new tab is selected? Wouldn’t it be nice if the objects that are going to reside inside those tabs could listen to that message and update accordingly?
To do this, I created a Base class and a Register, where my objects will register automatically upon instantiation (thanks to the Base class).
-
var InstanceRegister = new Class({
-
instances: [],
-
addInstance: function(object) {
-
this.instances.push(object);
-
},
-
broadcastMessage: function(msg) {
-
$A(this.instances).each(function(item, index) {
-
item.processMessage(msg);
-
});
-
}
-
});
-
var Register = new InstanceRegister();
-
-
var Base = new Class({
-
ClassName: 'Base',
-
Implements: Options,
-
initialize: function(options) {
-
this.setOptions(options);
-
Register.addInstance(this);
-
},
-
processMessage: function(msg) {
-
console.log(this.ClassName, ' msg received: ');
-
console.dir(msg);
-
},
-
sendMessage: function(msg) {
-
Register.broadcastMessage(msg);
-
}
-
});
As you can see, the register is just an array of Instances. Yes, Register is a global object, but it will be the only one we will need. Meanwhile, the Base class adds the new instance to the Register automatically. For convenience, the Base class has a sendMessage method. Also, for convenience, I like to add a ClassName property to all my classes in case I need it later for logging, instance class type identification, etc.
Now, thanks to MooTools, we can create our classes and make them inherit from Base. We can override the processMessages method and act accordingly:
-
var Tabs = new Class({
-
ClassName: 'Tabs',
-
Extends: Base,
-
…
-
activateTab: function(tab) {
-
…
-
this.sendMessage({msg:'tabActivated', data:tab});
-
}
-
});
-
-
var VideoPlayer = new Class({
-
ClassName: 'VideoPlayer',
-
Extends: Base,
-
…
-
processMessage: function(msg) {
-
if (msg.msg == 'tabActivated' && msg.data = 'video-tab') {
-
// Play video
-
}
-
}
-
});
The beautifulness of this code resides, as I mentioned before, in the absence of any object references. Tabs doesn’t know anything about the VideoPlayer class nor any other object listening to the messages. And the VideoPlayer doesn’t know anything about the Tabs class either. It only knows about the message it has to listen to. No object references, no methods, no callbacks.
Pay attention now. This is the best part! Whenever we instance our classes, no matter how many times we do, we don’t need variable references anymore:
-
new Tabs();
-
new VideoPlayer();
Nice, uh?
Since I implemented this class I use it a lot on every project at work. It makes my life easier, keeping my classes simple and independent from each other. It’s even better. We have got to a point where we have integrated this feature with our Flash components, so these send messages to the Register when needed and any JS object listening reacts to them as needed.
By doing this, even being unidirectional (Flash to JS only), we have achieved something great: from now on, our Flash objects don’t need to know anything about our JS objects at all. Just send a message to the register and done.
At any point, even from Firebug, you can send a message to the Register. This is very nice, even for debugging:
-
Register.broadcastMessage({msg:'hello',data:'world'});
A listener class
I found it is very nice, while in development, to have a Listener class debugging any message received. This way I don’t need to add a console.log call on all my classes to output received messages. The Listener will do it for me:
-
var Listener = new Class({
-
Extends: Base,
-
initialize: function() {
-
this.parent();
-
this.ignoreMessages = false;
-
},
-
processMessage: function(msg) {
-
if (msg.msg == 'stopListener') this.ignoreMessages = true;
-
if (msg.msg == 'startListener') this.ignoreMessages = false;
-
if (this.ignoreMessages) return;
-
console.log('Listener: msg received:');
-
console.dir(msg);
-
}
-
});
-
new Listener();
Even you can control the Listener by sending custom messages to it! Awesome!
Could this be achieved with custom events?
With Mootools, creating custom events is piece of cake. But from what I understand, custom events work only inside the object that is firing them. This is, if object A fires an event ‘customEvent’, you can only listen to it if you add a callback function when you instantiate that class:
-
var A = new Class({
-
Implements: Events,
-
initialize: function() {
-
document.body.addEvent('click', function() {
-
console.log('A: body clicked');
-
this.fireEvent('bodyClicked', [this]);
-
}.bind(this));
-
}
-
});
-
-
var B = new Class({
-
doSomething: function() {
-
console.log('B: doing something…');
-
}
-
});
-
-
new A({
-
onBodyClicked: function() {
-
// Tell B to do something (you need a reference to B!)
-
}
-
});
-
new B(); // Will never do something
Ideally, B should be able to listen to the bodyClicked event without passing any info when A is instantiated. But if I’m not mistaken, this is not possible.
Revised version
I decided that it would be cool to have the Messenger as something my classes could implement, instead of inherit from (Base). Also, it would be good if one object could register for a specific message only, which would improve performance too.
-
var NotificationServiceCenter = new Class({
-
instances: {},
-
addObserver: function(msg, instance) {
-
if (!this.instances[msg]) {
-
this.instances[msg] = [];
-
}
-
this.instances[msg].push(instance);
-
},
-
broadcastMessage: function(msg, data) {
-
if (this.instances[msg]) {
-
$A(this.instances[msg]).each(function(item, index) {
-
item.processMessage(msg, data);
-
});
-
}
-
}
-
});
-
var NotificationService = new NotificationServiceCenter();
-
-
var Messenger = new Class({
-
addMsgEvent: function(msg) {
-
NotificationService.addObserver(msg, this);
-
},
-
sendMessage: function(msg, data) {
-
NotificationService.broadcastMessage(msg, data);
-
},
-
processMessage: function(msg, data) {
-
// For implementation on the final Class
-
}
-
});
-
-
var A = new Class({
-
Implements: Messenger,
-
initialize: function() {
-
document.body.addEvent('click', function(){
-
console.log('A: document body clicked');
-
this.sendMessage('documentbodyclicked', 'Hello world!');
-
}.bind(this));
-
}
-
});
-
-
var B = new Class({
-
Implements: Messenger,
-
initialize: function() {
-
this.addMsgEvent('documentbodyclicked');
-
},
-
processMessage: function(msg, data) {
-
console.log('B: msg received: ', data);
-
}
-
});
-
-
new A();
-
new B();
Here you go!
MooTools 1.2.2 is here and it’s very cool
23 April 2009 | No Comments | 69 view(s)
What a great surprise it’s been to see the major updates in Mootools Core are around the Class object. Object Oriented javascript is the future and MooTools is the freeway to get there. Now, better than ever.
MooTools 1.2.2 is a mainly a bug fix release but it also includes an almost entirely new Class.js. The reasoning behind this is that the old Class.js didn’t play nicely with some advanced usages of this.parent() present in the new MooTools-More.
[...]
Other than providing the parent fixes, the new Class also features a much more robust inheritance model, especially when dealing with objects. For example, the objects you implement now in a class are merged if an object with the same name is found in the class prototype…
[...]
Another object-oriented feature we introduced is that now sub-objects are actually inherited Parent-to-Child. If you implement a new option in Animal, then Cat, which is a subclass of Animal, will get the new option as well, and so will every instance already existing.
Those are very cool features! Good job guys!
http://mootools.net/blog/2009/04/23/mootools-122-and-the-new-mootools-more/
Want more? Take a look at the new plugins available on Mootools More:
http://mootools.net/more
Synchronizing sounds (or trying to…)
10 April 2009 | No Comments | 75 view(s)
The purpose of this demo is to test and see how possible is to synchronize sounds with DOM effects while being played in different threads or timers. It looks like, while synchronizing sounds with DOM effects is quite simple and works fine, sounds played by different threads or timers get out of sync after a while.

See the demo in action.
Next step: build a sound controller class that can play sounds at some intervals, delays, etc
Setting up timers and intervals inside JS objects
7 April 2009 | 2 Comments | 90 view(s)
It may seem trivial but it has its tricky point. Usually, in procedural Javascript (this is, non object oriented programming), timers are set up passing the callback function on a string:
-
function hello() {
-
alert("hello");
-
}
-
// Will execute hello() after 10 seconds
-
setTimeout('hello()', 10000);
For this code to work, hello() has to be a global function (actually a function of the window object). Otherwise, when the timer times out, it won’t find it.
When writing object oriented code, one would like to call a function inside the object itself, not a global function. We can achieve this passing an anonymous function to the setTimeout function that calls our function:
-
var MyClass = new Class({
-
initialize: function() {
-
setTimeout(function() { this.hello(); }, 10000); // This wont work
-
},
-
hello: function() {
-
alert("hello");
-
}
-
});
The previous code wont work, since this inside the anonymous function points to the window object and not to our instance of MyClass. We solve this using the bind function provided by Mootools:
-
var MyClass = new Class({
-
initialize: function() {
-
setTimeout(function() { this.hello(); }.bind(this), 10000);
-
},
-
hello: function() {
-
alert("hello");
-
}
-
});
This code will work fine, but it still has a big problem. If we wanted to access any member or function of our instance inside the hello() function, it wouldn’t work. This is because when the timer times out, the context of our instance is lost. Inside the hello() function, this will point to the window object.
-
var MyClass = new Class({
-
initialize: function() {
-
this.text = 'hello';
-
setTimeout(function() { this.hello(); }.bind(this), 10000);
-
},
-
hello: function() {
-
alert(this.text); // This wont work
-
}
-
});
There are multiple ways to solve this issue but my favorite is to use the function call() of the function object. This function let’s you pass an object while calling your function that will become this inside it.
-
var MyClass = new Class({
-
initialize: function() {
-
this.text = 'hello';
-
setTimeout(function() { this.hello.call(this); }.bind(this), 10000);
-
},
-
hello: function() {
-
alert(this.text);
-
}
-
});
Now we can use this inside the hello() function and everything will work fine, no matter how many instances of MyClass we create.
-
var MyClass = new Class({
-
initialize: function(text) {
-
this.text = text;
-
setTimeout(function() { this.hello.call(this); }.bind(this), 10000);
-
},
-
hello: function() {
-
alert(this.text);
-
}
-
});
-
new MyClass('hello');
-
new MyClass('hi there!');
-
new MyClass('wassup?');
Enjoy :)