public
Description: Random things I've written in JavaScript. Most are untested and/or half-baked.
Homepage:
Clone URL: git://github.com/savetheclocktower/javascript-stuff.git
javascript-stuff / bindable.js
100644 44 lines (39 sloc) 1.043 kb
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
// Mixin for linking an element and a widget instance that controls its
// behavior. (Storing the instance as a property of the element itself
// leads to memory leaks.)
//
// Usage:
//
// var TableWidget = Class.create(Bindable, {
// initialize: function(element, options) {
// this.element = $(element);
// this.bindToElement();
// /* ... */
// }
//
// /* ... */
// });
//
// To retrieve an instance:
//
// $('some_table').getInstanceOf(TableWidget);
 
var Bindable = {
  bindToElement: function(element) {
    element = element || this.element;
    var id = element.identify();
 
    if (this.constructor._instances)
      this.constructor._instances = {};
 
    this.constructor._instances[id] = this;
  }
};
 
Element.addMethods({
  getInstanceOf: function(element, klass) {
    element = $(element);
    var instances = klass._instances;
 
    if (instances && element.id && instances[element.id]) {
      return instances[element.id];
    } else {
      throw "Must call Bindable#bindToElement first."
    }
  }
});