forked from clarissalittler/backbone-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathtextlist.js
77 lines (67 loc) · 2.07 KB
/
textlist.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
$(document).ready( function () {
var TextModel = Backbone.Model.extend({
defaults : {"value" : ""},
replace : function (str) {
this.set("value", str);
}
});
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(textVal+"<br><div>" + input + btn + "</div>");
},
initialize: function () {
this.model.on("change", this.render, this);
// last argument 'this' ensures that render's
// 'this' means the view, not the model
},
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
});
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.addView);
},
events : {
"click #addbutton" : "addModel"
},
addModel : function () {
this.collection.add({});
// collection adds a model, fires add event, then listener calls this.addView(model)
},
addView : function (newModel) {
newModel.set("value","Enter something here...");
var view = new TextView({model : newModel});
view.render();
this.$("#text-list").append(view.$el);
},
});
var textCollection = new TextCollection();
var textCollectionView = new TextCollectionView({ collection : textCollection});
textCollectionView.render();
$("#listdiv").append(textCollectionView.$el);
});