forked from component/view
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (71 loc) · 1.7 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* Module dependencies.
*/
var reactive = require('reactive')
, delegate = require('delegate')
, object = require('object')
, keys = object.keys;
/**
* Expose `View`.
*/
module.exports = View;
/**
* Initialize a view with the given `obj` / `el`.
*
* function ItemView(item) {
* View.call(this, item, tmpl.cloneNode(true));
* }
*
* @param {Object} obj
* @param {Element} el
* @api public
*/
function View(obj, el) {
this.el = el;
this.obj = obj;
this.view = reactive(el, obj, this);
this.bindings = {};
}
/**
* Bind to an event with the given `str`, and invoke `method`:
*
* this.bind('click .remove', 'remove')
* this.bind('click .complete', 'complete')
* this.bind('dblclick .info a', 'showDetails')
*
* @param {String} str
* @param {String} method
* @api public
*/
View.prototype.bind = function(str, method){
var parts = str.split(' ');
var event = parts.shift();
var selector = parts.join(' ');
var meth = this[method];
if (!meth) throw new TypeError('method "' + method + '" is not defined');
var fn = delegate.bind(this.el, selector, event, meth.bind(this));
this.bindings[str] = fn;
};
/**
* Unbind all listeners, all for a specific event, or
* a specific combination of event / selector.
*
* view.unbind()
* view.unbind('click')
* view.unbind('click .remove')
* view.unbind('click .details')
*
* @param {String} [str]
* @api public
*/
View.prototype.unbind = function(str){
if (str) {
var fn = this.bindings[str];
if (!fn) return;
var parts = str.split(' ');
var event = parts.shift();
delegate.unbind(this.el, event, fn);
} else {
keys(this.bindings).forEach(this.unbind.bind(this));
}
};