forked from clarissalittler/backbone-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 15
/
textlistServe.js
85 lines (74 loc) · 2.08 KB
/
textlistServe.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
$(document).ready( function () {
var TextModel = Backbone.Model.extend({
defaults : {"value" : ""},
initialize : function () {
this.fetch();
},
replace : function (str) {
this.set("value", str);
this.save();
}
});
var TextView = Backbone.View.extend({
render: function () {
var textVal = this.model.get("value");
var btn = '<button>Clear</button>';
var input = '<input type="text" value="' + textVal + '" />';
this.$el.html("<div>" + input + btn + "</div>");
},
initialize: function () {
this.model.on("change", this.render, this);
},
events : {
"click button" : "clear",
"keypress input" : "updateOnEnter"
},
replace : function () {
var str = this.$el.find("input").val();
this.model.replace(str);
},
clear: function () {
this.model.replace("");
},
updateOnEnter: function (e){
if(e.keyCode == 13) {
this.replace();
}
}
});
var TextCollection = Backbone.Collection.extend({
model : TextModel,
url : "/texts",
initialize: function () {
this.fetch();
}
});
var idCount = 0;
var TextCollectionView = Backbone.View.extend({
render : function () {
var btn = '<button id="addbutton">Add Text</button>';
var div = '<div id="text-list"></div>';
this.$el.html(div + btn);
},
initialize : function () {
this.listenTo(this.collection, 'add', this.addOne);
},
events : {
"click #addbutton" : "addCollection"
},
addOne : function (txt) {
txt.set("value","Enter something here...");
var view = new TextView({model : txt});
view.render();
this.$("#text-list").append(view.$el);
},
addCollection : function () {
this.collection.create({id : idCount});
idCount = idCount+1;
}
});
var textCollection = new TextCollection();
var textCollectionView = new TextCollectionView({ collection : textCollection});
textCollectionView.render();
$("#listdiv").append(textCollectionView.$el);
});