无法将集合获取数据同步到本地数据。 以下是代码
以下代码成功从服务器获取数据并呈现给视图。但是当我向集合中添加新元素时,它不会附加到服务器数据,它会创建新集合并添加到该集合。我应该如何将新数据附加到现有服务器数据。
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>Tag List</div>
<div id="tagTab">
<input type="text" name="name" id="name" />
<button id="addTag"> Add</button>
<ul id="tagList">
</ul>
</div>
<script type="text/template" id="tag-name-template">
<li>
<%= title %>
</li>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.0/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<script>
var app = {};
var tagModel = Backbone.Model.extend({
defaults: {
title: 'mak',
status: false
},
initialize: function() {
}
});
var tagCollection = Backbone.Collection.extend({
model: tagModel,
initialize: function() {
// console.log("collection added creation");
// this.fetch();
},
url: 'https://jsonplaceholder.typicode.com/posts',
parse: function(response) {
// console.log(response);
for (var i = 0; i < response.length; ++i) {
// s console.log();
this.add(response[i]);
// this.add(new tagModel({title:response[i].title}));
}
}
});
var tagNameView = Backbone.View.extend({
template: _.template($('#tag-name-template').html()),
initialize: function() {
this.render();
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
// return this.template(this.mode);
}
});
var tagTabView = Backbone.View.extend({
el: $('#tagTab'),
model: new tagCollection(),
initialize: function() {
this.render();
this.model.on('add', this.render, this);
this.model.fetch();
},
render: function() {
this.$('#tagList').html(''); // clean the todo list
// console.log(this.model);
for (var i = 0; i < this.model.length; ++i) {
// console.log(this.model.at(i));
this.$('#tagList').append(new tagNameView({
model: this.model.at(i)
}).el);
}
},
events: {
'click #addTag': 'add'
},
//To add the item to collections
add: function() {
// this.model.add(new tagModel({title:$("#name").val()}));
this.model.add({
title: $("#name").val()
});
$("#name").val("");
}
});
app.view = new tagTabView();
</script>
</body>
</html>
.....