UNPKG

2.77 kBMarkdownView Raw
1
2# events
3
4 Higher level dom event management with direct and delegate event handling support.
5
6 This component makes subscription management easy and unobtrusive since it does not muck with your view prototypes. Unbinding to "clean up" after your view is as simple as invoking `this.events.unbind()`, or more specific unbinds may be performed.
7
8 It's design to work with a "host" object, typically a view, that provides callbacks, making callback management much less tedious than libraries like jQuery.
9
10## Installation
11
12 $ component install component/events
13
14## Example
15
16```js
17var events = require('events');
18var el = document.querySelector('.user');
19
20var view = new UserView(el);
21
22function UserView(el) {
23 this.events = events(el, this);
24 this.events.bind('click .remove', 'remove');
25 this.events.bind('click .hide', 'hide');
26}
27
28UserView.prototype.remove = function(){
29 // remove the user
30 this.hide();
31};
32
33UserView.prototype.hide = function(){
34 // hide the view
35};
36
37UserView.prototype.destroy = function(){
38 // clean up anything you need to
39 this.events.unbind();
40};
41```
42
43## API
44
45### Events(el, obj)
46
47 Initialize a new events manager targetting the
48 given element. Methods are delegated to `obj`.
49
50### Events#bind(event, [method])
51
52 Bind direct event handlers or delegates with `event` and
53 invoke `method` when the event occurs, passing the event object.
54 When `method` is not defined the `event` name prefixed with "on" is used.
55
56 For example the following will invoke `onmousedown`, `onmousemove`,
57 and `onmouseup`:
58
59```js
60events.bind('mousedown')
61events.bind('mousemove')
62events.bind('mouseup')
63```
64
65 Alternatively you may specify the `method` name:
66
67```js
68events.bind('click', 'toggleDisplay')
69```
70
71 To use event delegation simply pass a selector after the
72 event name as shown here:
73
74```js
75events.bind('click .remove', 'remove')
76events.bind('click .close', 'hide')
77```
78
79 You may bind to the same element with several events if necessary,
80 for example here perhaps `.remove()` does not manually invoke `.hide()`:
81
82```js
83events.bind('click .remove', 'remove')
84events.bind('click .remove', 'hide')
85events.bind('click .close', 'hide')
86```
87
88 Addition arguments are passed to the callee, which
89 is helpful for slight variations of a method, for
90 example sorting:
91
92```js
93events.bind('click .sort-asc', 'sort', 'asc')
94events.bind('click .sort-dsc', 'sort', 'dsc')
95```
96
97### Events.unbind([event], [method])
98
99 There are three flavours of unbinding -- you may unbind _all_
100 event handlers, all specific to `event`, or all specific to
101 `event` and the given `method`. For example these are all valid:
102
103```js
104events.unbind('click', 'remove')
105events.unbind('click', 'hide')
106events.unbind('click')
107events.unbind()
108```
109
110## License
111
112 MIT