forked from pazguille/editable
/
index.js
74 lines (60 loc) · 1.64 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
/**
* Module dependencies.
*/
var Emitter = require('emitter');
/**
* Expose Editable
*/
exports = module.exports = Editable;
/**
* Editable
*/
function Editable(el, title) {
if (!(this instanceof Editable)) return new Editable(el, title);
this.init(el, title);
}
Emitter(Editable.prototype);
Editable.prototype.init = function (el, title) {
var that = this;
that.el = el;
that.title = title || 'Click to edit.';
that.content = that.el.innerHTML;
that.el.setAttribute('contentEditable', true);
that.el.setAttribute('title', that.title);
// W3C
if (that.el.addEventListener) {
that.el.addEventListener('keydown', function () {
that.onKeydown(event);
}, false);
that.el.addEventListener('blur', function () {
that.onBlur();
}, false);
// IE
} else if (that.el.attachEvent) {
that.el.attachEvent('onkeydown', function (event) {
that.onKeydown(event)
});
that.el.attachEvent('onblur', function () {
that.onBlur();
});
}
}
Editable.prototype.onKeydown = function (event) {
var esc = (event.which === 27),
enter = (event.which === 13);
if (esc) {
this.el.innerHTML = this.content;
this.el.blur();
this.emit('cancel', this.content);
} else if (enter) {
this.el.blur();
}
}
Editable.prototype.onBlur = function () {
this.el.removeAttribute('contentEditable');
if (this.content !== this.el.innerHTML) {
this.content = this.el.innerHTML;
this.emit('done', this.content);
}
}
Editable.prototype.destroy = function () {}