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 />

};<br />

EventUtil.removeHandler(document, “mouseup”, handleEvent);<br />

return dragdrop;<br />

}();<br />

This code defines three events: dragstart , drag , and dragend . Each of these events sets the dragged<br />

element as the target and provides x and y properties to indicate its current position. These are fired on<br />

the dragdrop object, which later is augmented with the enable() and disable() methods before<br />

being returned. This slight change in the module pattern allows the DragDrop object to support events<br />

such as the following:<br />

DragDrop.addHandler(“dragstart”, function(event){<br />

var status = document.getElementById(“status”);<br />

status.innerHTML = “Started dragging “ + event.target.id;<br />

});<br />

DragDrop.addHandler(“drag”, function(event){<br />

var status = document.getElementById(“status”);<br />

status.innerHTML += “ < br / > Dragged “ + event.target.id + “ to (“ + event.x +<br />

“,” + event.y + “)”;<br />

});<br />

DragDrop.addHandler(“dragend”, function(event){<br />

var status = document.getElementById(“status”);<br />

status.innerHTML += “ < br / > Dropped “ + event.target.id + “ at (“ + event.x +<br />

“,” + event.y + “)”;<br />

});<br />

Here, event handlers are added for each event of the DragDrop object. An element is used to display the<br />

current state and location of the dragged element. Once the element is dropped, you have a listing of all<br />

the intermediate steps it took since it was initially dragged.<br />

Adding custom events to DragDrop makes it a more robust object that can be used to manage complex<br />

drag-and-drop functionality in a web application.<br />

Summary<br />

Functions in JavaScript are quite powerful, because they are first - class objects. Using closures and<br />

function context switching, there are a number of powerful ways functions can be used. For example:<br />

❑<br />

❑<br />

❑<br />

❑<br />

It ’ s possible to create scope - safe constructors, ensuring that a constructor called without the new<br />

operator will not change the wrong context object.<br />

You can use lazy loading functions by delaying any code forking until the first time that the<br />

function is called.<br />

Function binding allows you to create functions that are always run in a specific context, and<br />

function currying allows you to create functions that have some of their arguments already<br />

filled in.<br />

Combining binding and currying gives you a way to execute any function, in any context, and<br />

with any arguments.<br />

615

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

Saved successfully!

Ooh no, something went wrong!