This repository was archived by the owner on Apr 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmartView.js
More file actions
125 lines (94 loc) · 2.84 KB
/
SmartView.js
File metadata and controls
125 lines (94 loc) · 2.84 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
var SmartView = Backbone.View.extend({
modelClass: Backbone.Model,
model: null,
selector: null,
_readyContinuations: null,
templateDelimeters: {
unescaped: {
open: "<%=",
close: "%>"
},
escaped: {
open: "<%-",
close: "%>"
}
},
initialize: function(options) {
this._parseOptions(options);
var attrs = this._parseFragment();
this._createModel(attrs);
},
render: function() {
if (!this.template) {
this._createTemplate();
}
this.$el.html(this.template(this.model.toJSON()));
return this;
},
ready: function(fn) {
if (this._hasModel) {
fn(this.model);
} else {
if (!this._readyContinuations) {
this._readyContinuations = [];
}
this._readyContinuations.push(fn);
}
},
_parseFragment: function() {
var attrs = {};
this.$("[data-attr]").each(function() {
attrs[$(this).data('attr')] = $(this).text();
});
return attrs;
},
_createTemplate: function() {
var $fragment = this.$el.clone();
var self = this;
$fragment.find('[data-attr]').each(function() {
if ($(this).data('escaped')) {
$(this).text(self.templateDelimeters.escaped.open + " " + $(this).data('attr') + " " + self.templateDelimeters.escaped.close);
} else {
$(this).text(self.templateDelimeters.unescaped.open + " " + $(this).data('attr') + " " + self.templateDelimeters.unescaped.close);
}
});
this.template = _.template($fragment.html().replace(/\<\;\%/g, "<%").replace(/\%\>\;/g, "%>"));
},
_createModel: function(attrs) {
this.model = new this.modelClass(attrs);
this._bindEvents();
this._addToCollection();
this._hasModel = true;
this._flushReady();
},
_parseOptions: function(options) {
if (options.selector) {
this.selector = options.selector;
}
if (options.modelClass) {
this.modelClass = options.modelClass;
}
if (options.templateDelimeters) {
this.templateDelimeters = options.templateDelimeters;
}
},
_bindEvents: function() {
if (this.model) {
this.model.on("change", function() {
this.render();
}, this);
}
},
_addToCollection: function() {
if (this.model && this.collection) {
this.collection.add(this.model);
}
},
_flushReady: function() {
if (this._readyContinuations) {
_.each(this._readyContinuations, function(fb) {
fn(this.model);
}, this);
}
}
});