04.11.2015 Views

javascript

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 18: Advanced Techniques<br />

Custom events using the EventTarget type can then be used as follows:<br />

function handleMessage(event){<br />

alert(“Message received: “ + event.message);<br />

}<br />

//create a new object<br />

var target = new EventTarget();<br />

//add an event handler<br />

target.addHandler(“message”, handleMessage);<br />

//fire the event<br />

target.fire({ type: “message”, message: “Hello world!”});<br />

//remove the handler<br />

target.removeHandler(“message”, handleMessage);<br />

//try again - there should be no handler<br />

target.fire({ type: “message”, message: “Hello world!”});<br />

In this code, the handleMessage() function is defined to handle a message event. It accepts the event<br />

object and outputs the message property. The target object ’ s addHandler() method is called, passing<br />

in ” message ” and the handleMessage() function. On the next line, fire() is called with an object<br />

literal containing two properties: type and message . This calls the event handlers for the message event<br />

so an alert will be displayed (from handleMessage() ). The event handler is then removed so that when<br />

the event is fired again, no alert will be displayed.<br />

Because this functionality is encapsulated in a custom type, other objects can inherit this behavior by<br />

inheriting from EventTarget , as in this example:<br />

function Person(name, age){<br />

EventTarget.call(this);<br />

this.name = name;<br />

this.age = age;<br />

}<br />

inheritPrototype(Person,EventTarget);<br />

Person.prototype.say = function(message){<br />

this.fire({type: “message”, message: message});<br />

};<br />

The Person type uses parasitic combination inheritance (see Chapter 6 ) to inherit from EventTarget .<br />

Whenever the say() method is called, an event is fired with the details of a message. It ’ s common for<br />

the fire() method to be called during other methods of a type, and quite uncommon for it to be called<br />

publicly. This code can then be used as follows:<br />

function handleMessage(event){<br />

alert(event.target.name + “ says: “ + event.message);<br />

}<br />

//create new person<br />

608

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!