我是BackboneJS/RequireJS中的n00b,我正在開發一個使用RESTful API的Web應用程序。 所以我這樣一個模型:Backbone.js - 如何通過表單保存模型併發布到服務器
型號/ pet.js
define([
'backbone'
], function(Backbone){
var PetModel = Backbone.Model.extend({
urlRoot: 'http://localhost:3000/pet',
idAttribute: '_id',
defaults: {
petId: "",
type: "",
name: "",
picture: "",
description: "",
breed: "",
size: "",
sex: "",
age: "",
adopted: false,
}
});
return PetModel;
});
集合:收藏/ pets.js
define([
'backbone',
'models/pet'
], function(Backbone, PetModel){
var PetsCollection = Backbone.Collection.extend({
url: 'http://localhost:3000/pets',
model: PetModel,
});
return PetsCollection;
});
並呈現一個視圖一種添加新模型的形式(也許它可能是另一種更優雅的方式) views/petAddNew.js
define([
'jquery',
'backbone',
'models/pet',
'collections/pets',
'text!templates/pet/addNew.html'
], function($, Backbone, PetModel, PetsCollection, petAddNewTemplate){
var PetAddNewView = Backbone.View.extend({
el: $('#formAdd'),
template: _.template(petAddNewTemplate),
events: {
'click #add' : 'submitAdd',
},
initialize: function() {
this.model = new PetModel();
this.collection = new PetsCollection();
_.bindAll(this, 'submitAdd');
},
render: function() {
var view = this;
view.$el.html(view.template);
return view;
},
submitAdd: function(e) {
//Save Animal model to server data
e.preventDefault();
var pet_data = JSON.stringify(this.getFormData(this.$el.find('form')));
this.model.save(pet_data);
this.collection.add(this.model);
return false
},
//Auxiliar function
getFormData: function(form) {
var unindexed_array = form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
return indexed_array;
},
});
return PetAddNewView;
});
所以當我提交表單時,我不會發布任何數據到服務器。我不知道如何解決它。 任何想法?提前致謝!
爲什麼不調試Backbone內發生的事情?在大多數情況下,這是解決問題的最快方式(與任何開源產品一樣)。 – 2013-04-30 14:51:54
是的,我用chrome中的console.log進行調試,var「pet_data」顯示了完整的JSON對象序列化的窗體,但方法「保存」不工作:( – 2013-04-30 15:04:12
謝謝@ J-unior我注意到,沒有調試在服務器端,我已經發現了錯誤,現在我很高興:P – 2013-05-01 08:58:36