-
Notifications
You must be signed in to change notification settings - Fork 220
/
Copy pathapp.js
106 lines (99 loc) · 2.45 KB
/
app.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
const URL = 'http://localhost:1337/'
// const URL ='http://your-app-name.herokuapp.com/'
require([
'libs/text!header.html',
'libs/text!home.html',
'libs/text!footer.html'],
function (
headerTpl,
homeTpl,
footerTpl) {
const ApplicationRouter = Backbone.Router.extend({
routes: {
'': 'home',
'*actions': 'home'
},
initialize: function() {
this.headerView = new HeaderView()
this.headerView.render()
this.footerView = new FooterView()
this.footerView.render()
},
home: function() {
this.homeView = new HomeView()
this.homeView.render()
}
})
const HeaderView = Backbone.View.extend({
el: '#header',
templateFileName: 'header.html',
template: headerTpl,
initialize: function() {
},
render: function() {
$(this.el).html(_.template(this.template))
}
})
const FooterView = Backbone.View.extend({
el: '#footer',
template: footerTpl,
render: function() {
this.$el.html(_.template(this.template))
}
})
const Message = Backbone.Model.extend({
url: URL + 'messages.json'
})
const MessageBoard = Backbone.Collection.extend ({
model: Message,
url: URL + 'messages.json'
})
const HomeView = Backbone.View.extend({
el: '#content',
template: homeTpl,
events: {
'click #send': 'saveMessage'
},
initialize: function() {
const homeView = this
homeView.collection = new MessageBoard()
homeView.collection.bind('refresh', homeView.render, homeView)
homeView.collection.fetch({
success: function(collection, response, options){
console.log('Fetched ', collection)
collection.trigger('refresh')
},
error: function(){
console.error('Error fetching messages')
}
})
homeView.collection.on('add', function(message) {
if (message.attributes._id) return false
message.save(null, {
success: function(message) {
homeView.collection.trigger('refresh')
console.log('Saved ', message)
},
error: function(message) {
console.log('error')
}
})
})
},
saveMessage: function(){
const newMessageForm = $('#new-message')
const username = newMessageForm.find('[name="username"]').val()
const message = newMessageForm.find('[name="message"]').val()
this.collection.add({
'username': username,
'message': message
})
},
render: function() {
console.log('Home view rendered')
$(this.el).html(_.template(this.template)(this.collection))
}
})
window.app = new ApplicationRouter()
Backbone.history.start()
})