gpt4 book ai didi

post - Backbone.js - 如何通过表单保存模型并发布到服务器

转载 作者:行者123 更新时间:2023-12-04 02:05:22 24 4
gpt4 key购买 nike

我是 BackboneJS/RequireJS 的 n00b,我正在开发一个使用 RESTful API 的 Web 应用程序。
所以我有一个这样的模型:

模型/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;
});

以及呈现表单以添加新模型的 View (也许有另一种更优雅的方式)
View /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;
});

因此,当我提交表单时,我不会将任何数据发布到服务器。我不知道如何修复它。
有什么想法吗?提前致谢!

最佳答案

您需要先设置属性,然后保存。

//Auxiliar function
getFormData: function(form) {
var self = this;
var unindexed_array = form.serializeArray();

$.map(unindexed_array, function(n, i){
self.model.set({
n['name']: n['value']
});
});
}

现在 this.model.save()工作(保存在服务器端)。

您可以在 fiddle 中看到它的工作原理.

关于post - Backbone.js - 如何通过表单保存模型并发布到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16302670/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com