YUI 3.x Home -

YUI Library Examples: Event: Creating an Arrow Event for DOM Subscription

Event: Creating an Arrow Event for DOM Subscription

This example will illustrate how to use the synthetic event creation API. We'll create an arrow event that fires in response to the user pressing the arrow keys (up, down, left, right) and adds a direction property to the generated event.

Subscribing to this new event will look like this:

  1. node.on("arrow", onArrowHandler);
  2.  
node.on("arrow", onArrowHandler);
 

Support will also be added for delegation, allowing a single subscriber from a node higher up the DOM tree, to listen for the new event emanating from its descendant elements.

  1. containerNode.delegate("arrow", onArrowHandler, ".robot");
  2.  
containerNode.delegate("arrow", onArrowHandler, ".robot");
 

Step 1. to the arrow event.

Step 2. Click on a robot and move it around with the arrow keys.

on, fire, and detach

The three interesting moments in the lifecycle of an event subscription are

  1. The event is subscribed to
  2. The event is fired
  3. The event is unsubscribed from

Create a new synthetic DOM event with Y.Event.define( name, config ). Define the implementation logic for the on and detach moments in the configuration. Typically the condition triggering the event firing is set up in the on phase.

  1. Y.Event.define("arrow", {
  2. on: function (node, sub, notifier) {
  3. // what happens when a subscription is made
  4.  
  5. // if (condition) {
  6. notifier.fire(); // subscribers executed
  7. // }
  8. },
  9.  
  10. detach: function (node, sub, notifier) {
  11. // what happens when a subscription is removed
  12. }
  13. } );
Y.Event.define("arrow", {
    on: function (node, sub, notifier) {
        // what happens when a subscription is made
 
        // if (condition) {
            notifier.fire(); // subscribers executed
        // }
    },
 
    detach: function (node, sub, notifier) {
        // what happens when a subscription is removed
    }
} );

In the case of arrow handling, the trigger is simply a key event with a keyCode between 37 and 40. There are a few browser quirks with arrow handling that warrant listening to keydown for some browsers and keypress for others, so we'll take care of that transparently for arrow subscribers.

  1. Y.Event.define("hover", {
  2. on: function (node, sub, notifier) {
  3. var directions = {
  4. 37: 'left',
  5. 38: 'up',
  6. 39: 'right',
  7. 40: 'down'
  8. };
  9.  
  10. // Webkit and IE repeat keydown when you hold down arrow keys.
  11. // Opera links keypress to page scroll; others keydown.
  12. // Firefox prevents page scroll via preventDefault() on either
  13. // keydown or keypress.
  14. // Bummer to sniff, but can't test the repeating behavior, and a
  15. // feature test for the scrolling would more than double the code size.
  16. var eventName = (Y.UA.webkit || Y.UA.ie) ? 'keydown' : 'keypress';
  17.  
  18. // To make detaching the associated DOM event easy, store the detach
  19. // handle from the DOM subscription on the synthethic subscription
  20. // object.
  21. sub._detacher = node.on(eventName, function (e) {
  22. // Only notify subscribers if one of the arrow keys was pressed
  23. if (directions[e.keyCode]) {
  24. // Add the extra property
  25. e.direction = directions[e.keyCode];
  26.  
  27. // Firing the notifier event executes the arrow subscribers
  28. // Pass along the key event, which will be renamed "arrow"
  29. notifier.fire(e);
  30. }
  31. });
  32. },
  33.  
  34. detach: function (node, sub, notifier) {
  35. // Detach the key event subscription using the stored detach handle
  36. sub._detacher.detach();
  37. }
  38. } );
Y.Event.define("hover", {
    on: function (node, sub, notifier) {
        var directions = {
            37: 'left',
            38: 'up',
            39: 'right',
            40: 'down'
        };
 
        // Webkit and IE repeat keydown when you hold down arrow keys.
        // Opera links keypress to page scroll; others keydown.
        // Firefox prevents page scroll via preventDefault() on either
        // keydown or keypress.
        // Bummer to sniff, but can't test the repeating behavior, and a
        // feature test for the scrolling would more than double the code size.
        var eventName = (Y.UA.webkit || Y.UA.ie) ? 'keydown' : 'keypress';
 
        // To make detaching the associated DOM event easy, store the detach
        // handle from the DOM subscription on the synthethic subscription
        // object.
        sub._detacher = node.on(eventName, function (e) {
            // Only notify subscribers if one of the arrow keys was pressed
            if (directions[e.keyCode]) {
                // Add the extra property
                e.direction = directions[e.keyCode];
 
                // Firing the notifier event executes the arrow subscribers
                // Pass along the key event, which will be renamed "arrow"
                notifier.fire(e);
            }
        });
    },
 
    detach: function (node, sub, notifier) {
        // Detach the key event subscription using the stored detach handle
        sub._detacher.detach();
    }
} );

Add Delegation Support

Since the arrow event is simply a filtered keydown or keypress event, no special handling needs to be done for delegate subscriptions. We will extract the key event handler and use it for both on("arrow", ...) and delegate("arrow", ...) subscriptions.

  1. Y.Event.define("arrow", {
  2. // Webkit and IE repeat keydown when you hold down arrow keys.
  3. // Opera links keypress to page scroll; others keydown.
  4. // Firefox prevents page scroll via preventDefault() on either
  5. // keydown or keypress.
  6. _event: (Y.UA.webkit || Y.UA.ie) ? 'keydown' : 'keypress',
  7.  
  8. _keys: {
  9. '37': 'left',
  10. '38': 'up',
  11. '39': 'right',
  12. '40': 'down'
  13. },
  14.  
  15. _keyHandler: function (e, notifier) {
  16. if (this._keys[e.keyCode]) {
  17. e.direction = this._keys[e.keyCode];
  18. notifier.fire(e);
  19. }
  20. },
  21.  
  22. on: function (node, sub, notifier) {
  23. // Use the extended subscription signature to set the 'this' object
  24. // in the callback and pass the notifier as a second parameter to
  25. // _keyHandler
  26. sub._detacher = node.on(this._event, this._keyHandler,
  27. this, notifier);
  28. },
  29.  
  30. detach: function (node, sub, notifier) {
  31. sub._detacher.detach();
  32. },
  33.  
  34. // Note the delegate handler receives a fourth parameter, the filter
  35. // passed (e.g.) container.delegate('click', callback, '.HERE');
  36. // The filter could be either a string or a function.
  37. delegate: function (node, sub, notifier, filter) {
  38. sub._delegateDetacher = node.delegate(this._event, this._keyHandler,
  39. filter, this, notifier);
  40. },
  41.  
  42. // Delegate uses a separate detach function to facilitate undoing more
  43. // complex wiring created in the delegate logic above. Not needed here.
  44. detachDelegate: function (node, sub, notifier) {
  45. sub._delegateDetacher.detach();
  46. }
  47. });
Y.Event.define("arrow", {
    // Webkit and IE repeat keydown when you hold down arrow keys.
    // Opera links keypress to page scroll; others keydown.
    // Firefox prevents page scroll via preventDefault() on either
    // keydown or keypress.
    _event: (Y.UA.webkit || Y.UA.ie) ? 'keydown' : 'keypress',
 
    _keys: {
        '37': 'left',
        '38': 'up',
        '39': 'right',
        '40': 'down'
    },
 
    _keyHandler: function (e, notifier) {
        if (this._keys[e.keyCode]) {
            e.direction = this._keys[e.keyCode];
            notifier.fire(e);
        }
    },
 
    on: function (node, sub, notifier) {
        // Use the extended subscription signature to set the 'this' object
        // in the callback and pass the notifier as a second parameter to
        // _keyHandler
        sub._detacher = node.on(this._event, this._keyHandler,
                                this, notifier);
    },
 
    detach: function (node, sub, notifier) {
        sub._detacher.detach();
    },
 
    // Note the delegate handler receives a fourth parameter, the filter
    // passed (e.g.) container.delegate('click', callback, '.HERE');
    // The filter could be either a string or a function.
    delegate: function (node, sub, notifier, filter) {
        sub._delegateDetacher = node.delegate(this._event, this._keyHandler,
                                              filter, this, notifier);
    },
 
    // Delegate uses a separate detach function to facilitate undoing more
    // complex wiring created in the delegate logic above.  Not needed here.
    detachDelegate: function (node, sub, notifier) {
        sub._delegateDetacher.detach();
    }
});

Use it

Subscribe to the new event or detach the event as you would any other DOM event.

  1. function move(e) {
  2. // to prevent page scrolling
  3. e.preventDefault();
  4.  
  5. // See full code listing to show the data set up
  6. var xy = this.getData();
  7.  
  8. switch (e.direction) {
  9. case 'up': xy.y -= 10; break;
  10. case 'down': xy.y += 10; break;
  11. case 'left': xy.x -= 10; break;
  12. case 'right': xy.x += 10; break;
  13. }
  14.  
  15. this.transition({
  16. top : (xy.y + 'px'),
  17. left: (xy.x + 'px'),
  18. duration: .2
  19. });
  20. }
  21.  
  22. // Subscribe using node.on("arrow", ...);
  23. Y.one("#A").on("arrow", move),
  24. Y.one("#B").on("arrow", move)
  25.  
  26. // OR using container.delegate("arrow", ...);
  27. subs = Y.one('#demo').delegate('arrow', move, '.robot');
function move(e) {
    // to prevent page scrolling
    e.preventDefault();
 
    // See full code listing to show the data set up
    var xy = this.getData();
 
    switch (e.direction) {
        case 'up':    xy.y -= 10; break;
        case 'down':  xy.y += 10; break;
        case 'left':  xy.x -= 10; break;
        case 'right': xy.x += 10; break;
    }
 
    this.transition({
        top : (xy.y + 'px'),
        left: (xy.x + 'px'),
        duration: .2
    });
}
 
// Subscribe using node.on("arrow", ...);
Y.one("#A").on("arrow", move),
Y.one("#B").on("arrow", move)
 
// OR using container.delegate("arrow", ...);
subs = Y.one('#demo').delegate('arrow', move, '.robot');

Bonus Step: to the Gallery!

Synthetic events are perfect candidates for Gallery modules. There are a number already hosted there, and there are plenty of UI interaction patterns that would benefit from being encapsulated in synthetic events.

This event would look like this as a gallery module:

  1. YUI.add("gallery-event-arrow", function (Y) {
  2. Y.Event.define("arrow", {
  3. // Webkit and IE repeat keydown when you hold down arrow keys.
  4. // Opera links keypress to page scroll; others keydown.
  5. // Firefox prevents page scroll via preventDefault() on either
  6. // keydown or keypress.
  7. _event: (Y.UA.webkit || Y.UA.ie) ? 'keydown' : 'keypress',
  8.  
  9. _keys: {
  10. '37': 'left',
  11. '38': 'up',
  12. '39': 'right',
  13. '40': 'down'
  14. },
  15.  
  16. _keyHandler: function (e, notifier) {
  17. if (this._keys[e.keyCode]) {
  18. e.direction = this._keys[e.keyCode];
  19. notifier.fire(e);
  20. }
  21. },
  22.  
  23. on: function (node, sub, notifier) {
  24. sub._detacher = node.on(this._event, this._keyHandler,
  25. this, notifier);
  26. },
  27.  
  28. detach: function (node, sub, notifier) {
  29. sub._detacher.detach();
  30. },
  31.  
  32. delegate: function (node, sub, notifier, filter) {
  33. sub._delegateDetacher = node.delegate(this._event, this._keyHandler,
  34. filter, this, notifier);
  35. },
  36.  
  37. detachDelegate: function (node, sub, notifier) {
  38. sub._delegateDetacher.detach();
  39. }
  40. });
  41. }, '0.0.1', { requires: ['event-synthetic'] });
YUI.add("gallery-event-arrow", function (Y) {
    Y.Event.define("arrow", {
        // Webkit and IE repeat keydown when you hold down arrow keys.
        // Opera links keypress to page scroll; others keydown.
        // Firefox prevents page scroll via preventDefault() on either
        // keydown or keypress.
        _event: (Y.UA.webkit || Y.UA.ie) ? 'keydown' : 'keypress',
 
        _keys: {
            '37': 'left',
            '38': 'up',
            '39': 'right',
            '40': 'down'
        },
 
        _keyHandler: function (e, notifier) {
            if (this._keys[e.keyCode]) {
                e.direction = this._keys[e.keyCode];
                notifier.fire(e);
            }
        },
 
        on: function (node, sub, notifier) {
            sub._detacher = node.on(this._event, this._keyHandler,
                                    this, notifier);
        },
 
        detach: function (node, sub, notifier) {
            sub._detacher.detach();
        },
 
        delegate: function (node, sub, notifier, filter) {
            sub._delegateDetacher = node.delegate(this._event, this._keyHandler,
                                                  filter, this, notifier);
        },
 
        detachDelegate: function (node, sub, notifier) {
            sub._delegateDetacher.detach();
        }
    });
}, '0.0.1', { requires: ['event-synthetic'] });

Full Code Listing

  1. YUI().use("event-synthetic", "node", "transition", function (Y) {
  2.  
  3. Y.Event.define("arrow", {
  4. // Webkit and IE repeat keydown when you hold down arrow keys.
  5. // Opera links keypress to page scroll; others keydown.
  6. // Firefox prevents page scroll via preventDefault() on either
  7. // keydown or keypress.
  8. _event: (Y.UA.webkit || Y.UA.ie) ? 'keydown' : 'keypress',
  9.  
  10. _keys: {
  11. '37': 'left',
  12. '38': 'up',
  13. '39': 'right',
  14. '40': 'down'
  15. },
  16.  
  17. _keyHandler: function (e, notifier) {
  18. if (this._keys[e.keyCode]) {
  19. e.direction = this._keys[e.keyCode];
  20. notifier.fire(e);
  21. }
  22. },
  23.  
  24. on: function (node, sub, notifier) {
  25. sub._detacher = node.on(this._event, this._keyHandler,
  26. this, notifier);
  27. },
  28.  
  29. detach: function (node, sub, notifier) {
  30. sub._detacher.detach();
  31. },
  32.  
  33. delegate: function (node, sub, notifier, filter) {
  34. sub._delegateDetacher = node.delegate(this._event, this._keyHandler,
  35. filter, this, notifier);
  36. },
  37.  
  38. detachDelegate: function (node, sub, notifier) {
  39. sub._delegateDetacher.detach();
  40. }
  41. });
  42.  
  43.  
  44. var robotA = Y.one('#A'),
  45. robotB = Y.one('#B'),
  46. subs;
  47.  
  48. robotA.setData('x', parseInt(robotA.getStyle('left'), 10));
  49. robotA.setData('y', parseInt(robotA.getStyle('top'), 10));
  50. robotB.setData('x', parseInt(robotB.getStyle('left'), 10));
  51. robotB.setData('y', parseInt(robotB.getStyle('top'), 10));
  52.  
  53. function move(e) {
  54. // to prevent page scrolling
  55. e.preventDefault();
  56.  
  57. var xy = this.getData();
  58.  
  59. switch (e.direction) {
  60. case 'up': xy.y -= 10; break;
  61. case 'down': xy.y += 10; break;
  62. case 'left': xy.x -= 10; break;
  63. case 'right': xy.x += 10; break;
  64. }
  65.  
  66. this.transition({
  67. top : (xy.y + 'px'),
  68. left: (xy.x + 'px'),
  69. duration: .2
  70. });
  71. }
  72.  
  73. function detachSubs() {
  74. if (subs) {
  75. subs.detach();
  76. subs = null;
  77. }
  78. }
  79.  
  80. Y.one("#attach").on("click", function (e) {
  81. detachSubs();
  82.  
  83. if (Y.one("#delegate").get('checked')) {
  84. subs = Y.one('#demo').delegate('arrow', move, '.robot');
  85. } else {
  86. subs = new Y.EventHandle([
  87. robotA.on("arrow", move),
  88. robotB.on("arrow", move)
  89. ]);
  90. }
  91. });
  92.  
  93. Y.one("#detach").on("click", detachSubs);
  94.  
  95. });
YUI().use("event-synthetic", "node", "transition", function (Y) {
 
    Y.Event.define("arrow", {
        // Webkit and IE repeat keydown when you hold down arrow keys.
        // Opera links keypress to page scroll; others keydown.
        // Firefox prevents page scroll via preventDefault() on either
        // keydown or keypress.
        _event: (Y.UA.webkit || Y.UA.ie) ? 'keydown' : 'keypress',
 
        _keys: {
            '37': 'left',
            '38': 'up',
            '39': 'right',
            '40': 'down'
        },
 
        _keyHandler: function (e, notifier) {
            if (this._keys[e.keyCode]) {
                e.direction = this._keys[e.keyCode];
                notifier.fire(e);
            }
        },
 
        on: function (node, sub, notifier) {
            sub._detacher = node.on(this._event, this._keyHandler,
                                    this, notifier);
        },
 
        detach: function (node, sub, notifier) {
            sub._detacher.detach();
        },
 
        delegate: function (node, sub, notifier, filter) {
            sub._delegateDetacher = node.delegate(this._event, this._keyHandler,
                                                  filter, this, notifier);
        },
 
        detachDelegate: function (node, sub, notifier) {
            sub._delegateDetacher.detach();
        }
    });
 
 
    var robotA = Y.one('#A'),
        robotB = Y.one('#B'),
        subs;
 
    robotA.setData('x', parseInt(robotA.getStyle('left'), 10));
    robotA.setData('y', parseInt(robotA.getStyle('top'), 10));
    robotB.setData('x', parseInt(robotB.getStyle('left'), 10));
    robotB.setData('y', parseInt(robotB.getStyle('top'), 10));
 
    function move(e) {
        // to prevent page scrolling
        e.preventDefault();
 
        var xy = this.getData();
 
        switch (e.direction) {
            case 'up':    xy.y -= 10; break;
            case 'down':  xy.y += 10; break;
            case 'left':  xy.x -= 10; break;
            case 'right': xy.x += 10; break;
        }
 
        this.transition({
            top : (xy.y + 'px'),
            left: (xy.x + 'px'),
            duration: .2
        });
    }
 
    function detachSubs() {
        if (subs) {
            subs.detach();
            subs = null;
        }
    }
 
    Y.one("#attach").on("click", function (e) {
        detachSubs();
 
        if (Y.one("#delegate").get('checked')) {
            subs = Y.one('#demo').delegate('arrow', move, '.robot');
        } else {
            subs = new Y.EventHandle([
                robotA.on("arrow", move),
                robotB.on("arrow", move)
            ]);
        }
    });
 
    Y.one("#detach").on("click", detachSubs);
 
});

Copyright © 2011 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings