Reputation: 45
I'm trying to save the form data to a server using a Deployd API; but when i click the save button, a new document it's created at the server but it contain no data. I don't understand how it can work; i guess i have to pass the data to the model to be saved? How do i do that? I thought that the view was already linked with the template and model. I'm using Requirejs, MarionetteJS and Handlebars. Here is the code.
MODEL:
define(['underscore','backbone'], function(_, Backbone){
var Student= Backbone.Model.extend({
urlRoot: '/students',
defaults: {
nameStudent: '',
lastnameStudent: ''
},
initialize: function(){
console.log('studentModel: initiated');
},
});
return Student;
});
VIEW:
define([
'jquery',
'underscore',
'backbone',
'marionette',
'handlebars',
'js/models/student',
'text!templates/forms/studentFormAdd.html'
], function($, _, Backbone, Marionette, Handlebars, studentModel, studentFormAddTemp){
var studentFormAdd = Backbone.Marionette.ItemView.extend({
model: studentModel,
template: Handlebars.compile(studentFormAddTemp),
events: {
'click #saveBtn': function(){
this.model.save();
console.log(this.model.toJSON());
console.log('saveBtn event: initiated');
}
},
initialize: function(){
console.log('studentFormAdd: initiated');
this.model = new studentModel();
this.model.on('change', this.render);
},
});
My template has the following sintax:
<div>
<form>
Student Name<br>
<input type="text" name="nameStudent" value="{{nameStudent}}" placeholder="Student name"/>
<br>
Student lastname<br>
<input type="text" name="lastnameStudent" value="{{lastnameStudent}}" placeholder="Student lastname"/><br>
</form>
</div>
Upvotes: 1
Views: 325
Reputation: 2155
Backbone doesn't use two way binding, so:
this.model.save();
in your saveBtn
event handler is empty. If you want realtime two-way binding, you can use:
https://github.com/theironcook/Backbone.ModelBinder or https://github.com/NYTimes/backbone.stickit
If you wan't to simply consume the form data on submit and save it in a model, you can use https://github.com/marionettejs/backbone.syphon.
var data = Backbone.Syphon.serialize(this);
this.model.set(data);
this.model.save();
Upvotes: 1