-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollectionbinder.js
More file actions
67 lines (58 loc) · 1.96 KB
/
Copy pathcollectionbinder.js
File metadata and controls
67 lines (58 loc) · 1.96 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
(function() {
define(['backbone', 'underscore'], function(Backbone, _) {
var CollectionBinder;
if (!(Backbone != null)) {
throw "Backbone's gotta be loaded first, brah";
}
if (!(_ != null)) {
throw "Underscore is quintessential, load it first";
}
return CollectionBinder = (function() {
function CollectionBinder(view, collection, template) {
var regex;
this.view = view;
this.collection = collection;
this.template = template;
regex = new RegExp("^[\\s\\w]*<([\\w]+)");
this.topLevelElement = regex.exec(this.template)[1];
}
CollectionBinder.prototype.bind = function() {
var model, _i, _len, _ref,
_this = this;
_ref = this.collection.models;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
model = _ref[_i];
bindModel(model);
}
this.collection.on("add", function(model) {
return _this.bindModel(model);
});
return this.collection.on("remove", function(model) {
return _this.removeModel(model);
});
};
CollectionBinder.prototype.uniqueId = function(length) {
var id;
if (length == null) {
length = 8;
}
id = "";
while (id.length < length) {
id += Math.random().toString(36).substr(2);
}
return id.substr(0, length);
};
CollectionBinder.prototype.bindModel = function(model) {
var modelEl;
model.bindIdentifier = this.uniqueId();
modelEl = Backbone.$(_.template(this.template, model.toJSON()));
modelEl.attr("data-bindid", model.bindIdentifier);
return this.view.$el.append(modelEl);
};
CollectionBinder.prototype.removeModel = function(model) {
return Backbone.$(this.topLevelElement + '[data-bindid="' + model.bindIdentifier + '"]').remove();
};
return CollectionBinder;
})();
});
}).call(this);