我正在运行Django + Backbone.js而.save()无效。我究竟做错了什么?这是我的主干javascript代码。我正在尝试实现优先级列表,我无法弄清楚如何POST回服务器。当我尝试时,Chromium甚至没有看到尝试过的帖子: T = new Task(); T.save();
在控制台中。
//$(function() {
/**
* Model: Task
* name, date, importance
*/
window.Task = Backbone.Model.extend({
urlRoot: '/api/v1/task/',
initialize: function() {
console.log("New task: " + JSON.stringify(this.toJSON()));
}
, defaults: function() {
return {
date: new Date()
, name: "New event"
, importance: 0
};
}
});
/**
* Collections: Calendar
*/
window.Calendar = Backbone.Collection.extend({
//urlRoot: '/api/v1/calendar',
initialize: function() {
console.log("New calendar: " + JSON.stringify(this.toJSON()));
}
, model: Task
, comparator: function(task) {
return task.get("date");
}
/*
, before: function(thresholdDate) {
return this.filter( function(task) {
task.get('date') < thresholdDate;
});
}
*/
});
window.TaskView = Backbone.View.extend({
tagName: "li"
});
now = new Date();
Day = Backbone.Collection.extend({
model: Task,
url: '/api/v1/task/?format=json&calendar__id=1&date='+ now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate(),
parse: function(response) {
return response.objects;
},
comparator: function(task){
return task.get('priority');}
});
Month = Backbone.Collection.extend({
model: Task,
url: 'api/v1/task/?format=json&date__month='+(now.getMonth()+1),
parse: function(response){
return response.objects;
},
comparator: function(task){
return task.get('priority');}
});
Year = Backbone.Collection.extend({
model: Task,
url: 'api/v1/task/?format=json&date__year='+now.getFullYear(),
parse: function(response){
return response.objects;
},
comparator: function(task){
return task.get('priority');}
});
// required for saving
Backbone.sync = function(method, model) {
console.log(method + ": " + JSON.stringify(model));
model.id = 1;
};
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
var dict = $('form').serializeObject();
var new_task = new Backbone.Model({
date: toString(dict.date),
name: toString(dict.name),
priority: toString(dict.priority)});
console.log("new_task =" + new_task);
new_task.save();
console.log(dict);
return false;
});
});
TaskView = Backbone.View.extend({
el: $("div#app"),
render: function() {
$(thi.el).html(this.template(this.model.toJSON()));
}
});
//});
答案 0 :(得分:1)
您已重写Backbone.sync
方法以仅记录控制台消息。
如果覆盖Backbone.sync
,则需要在该方法中手动执行保存逻辑。
因此,要么删除覆盖Backbone.sync
的代码,要么在该代码中添加ajax调用以执行保存。