我以某种方式制作了基本待办事项列表,但无法在服务器上保存任务。现在开始实现服务器端,但很难掌握所有应该如何相互通信的整个想法。这是我尝试做的事情:在TodoView(渲染列表)中,我创建了一个带有输入值的模型,并通过save()方法尝试在服务器上发布。正如我所说,我缺乏掌握一般概念,如何将json保存在服务器上(它将保存在我传入Collection的tasks.json文件中吗?)。任何帮助,提示和方向将不胜感激!
这是我的Backbone代码
var Model = Backbone.Model.extend({
default: {
task: '',
completed: false
}
});
var Collection = Backbone.Collection.extend({
model: Model,
url: '/tasks.json'
});
var ItemView = Backbone.View.extend({
tagName: 'li',
render: function () {
this.$el.data('cid', this.model.cid);
this.$el.html(this.model.toJSON().task);
return this;
}
});
var TodoView = Backbone.View.extend({
el: '#todo',
initialize: function () {
this.collection = new Collection();
this.collection.on('add', this.render, this);
// this.collection.fetch();
},
events: {
'click .add': 'add',
'dblclick li': 'destroy',
'keydown': 'keyEvent'
},
add: function () {
// this.collection.add(new Model({ //adding input as an model to collection
// task: this.$('#todo').val(),
// completed: false
// }));
var taskData = {
task: this.$('#todo').val(),
completed: false
};
var newlyCreatedModel = new Model({
task: this.$('#todo').val(),
completed: false
});
newlyCreatedModel.save({
// url: '/tasks.json',
data: JSON.stringify(taskData),
type: 'POST',
contentType: 'application/json'
});
this.$('#todo').val(''); //clearing input field
this.$('#todo').focus(); //focusing input after adding task
},
keyEvent: function (e) {
if (e.which === 13) {
this.add();
}
},
destroy: function (e) {
// e.preventDefault();
var id = $(e.target).data('cid');
var model = this.collection.get(id);
model.destroy();
e.target.remove();
},
render: function (newModel) {
var self = this,
todoView;
todoView = new ItemView({
model: newModel
});
self.$('.list').append(todoView.render().el);
return this;
}
});
var trigger = new TodoView();
这是我的html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Validation</title>
</head>
<body>
<div id="todo">
<label for="todo">Write your task</label>
<input type="text" id='todo'><button class='add'>add</button>
<ul class='list'>
</ul>
</div>
<script src="jquery.js"></script>
<script src="underscore.js"></script>
<script src="backbone.js"></script>
<script src="main.js"></script>
</body>
</html>
最后这是我的服务器在express.js
的帮助下在node.js上编写的 var express = require('express');
var server = express();
server.use(express.static(__dirname + '/test'));
server.post('/somepath', function (req, res) {
var bodyStr = '';
req.on('data', function (chunk) {
bodyStr += chunk.toString();
});
req.on('end', function (chunk) {
// res.send(bodyStr);
console.log(bodyStr);
});
});
var server = server.listen(8888);