tags:

views:

71

answers:

2

I'm reading "JavaScript the Good Parts" and it mentions cascades as a way to do method chaining in JavaScript but I can't find any code that explains how these methods should be implemented.

getElement('myBoxDiv').
move(350, 150).
width(100).
height(100).
color('red').
border('10px outset').
padding('4px').
appendText("Please stand by").
on('mousedown', function (m) {
    this.startDrag(m, this.getNinth(m));
}).
on('mousemove', 'drag').
on('mouseup', 'stopDrag').
later(2000, function (  ) {
    this.
        color('yellow').
        setHTML("What hath God wraught?").
        slide(400, 40, 200, 200);
}).
tip('This box is resizeable');
+3  A: 

The trick is that the method itself should only return this. That way, each time you chain these methods together, the object itself is the base of the call.

SomeObj.width(40) would then return just SomeObj, so adding the call .height(50) would function, and continue along.

Tony k
+1  A: 

This is basically the way JQuery works. The idea is to make each of those functions return objects which contain those functions again so to speak.

EDIT: You can download JQuery and look at the source code for it, because this is exactly what is going on in that library.

Deniz Dogan