forked from larrymyers/backbone-koans
-
Notifications
You must be signed in to change notification settings - Fork 5
/
tooterApp.js
115 lines (92 loc) · 3.12 KB
/
tooterApp.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
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
/*global $, _, Backbone */
(function() {
var Toot = Backbone.Model.extend({
defaults: function() {
return {
user: 'Mario',
message: 'Squishing Goombas, collecting coins.',
created_on: new Date()
};
},
initialize: function() {
// Capitalize the user's name associated with this Toot.
var userName = this.get('user');
userName = userName.slice(0,1).toUpperCase() + userName.slice(1).toLowerCase();
this.set({ user: userName }, { silent: true });
},
validate: function(attrs) {
if (_.isString(attrs.user) && attrs.user.length === 0) {
return 'Must have a user.';
}
if (_.isString(attrs.message) && attrs.message.length === 0) {
return 'Must contain a message.';
}
}
});
var Toots = Backbone.Collection.extend({
model: Toot,
url: '/toots/'
});
var TootView = Backbone.View.extend({
tagName: 'li',
initialize: function(options) {
this.options = options || {};
_.defaults(this.options, {
parentElt: 'body'
});
},
render: function() {
var model = this.model;
var content = _.template($('#tootViewTmpl').html())({
iconUrl: '',
message: this.model.get('message')
});
$(this.el).html(content);
$(this.options.parentElt).append(this.el);
}
});
var TootApp = Backbone.View.extend({
events: {
'keypress .tootInput': 'createToot'
},
toots: new Toots(),
initialize: function(options) {
this.options = options || {};
_.defaults(this.options, {
parentElt: 'body'
});
this.markup = _.template($('#tooterAppTmpl').html());
$(this.options.parentElt).append(this.el);
$(this.el).append(this.markup());
this.toots.bind('add', this.addToot, this);
this.toots.bind('reset', function(toots) {
toots.each(function(toot) {
this.addToot(toot);
}, this);
}, this);
this.toots.fetch();
},
addToot: function(toot) {
var view = new TootView({
parentElt: this.$('.tootList'),
model: toot
}).render();
},
createToot: function(evt) {
var text = this.$('.tootInput').val();
if (!text || evt.keyCode !== 13) {
return;
}
this.toots.create({
user: 'Me',
message: text
});
}
});
window.Tooter = {
Toot: Toot,
Toots: Toots,
TootView: TootView,
TootApp: TootApp
};
})();