查看TODO app in backbone way的一个很好的例子。
我还建议您阅读Backbone's documentation 并查看源代码。
它将记录在案,因此您可以在那里找到所需的一切,如果没有查看source。
您的表单的简单实现可以这样实现:
为了通过 REST 创建用户模型与 API 交互和数据交换:
var UserModel = Backbone.Model.extend({
urlRoot: 'your/api/path',
default: { // this will be setted when model attributes are empty
firstname: 'Default Name',
lastname: 'Default Lastname'
}
});
表单视图,它将为您呈现表单并将模型的属性绑定到表单的元素:
var UserForm = Backbone.View.extend({
initialize: function() {
this.render();
},
el: '.form-container', // this will attach view to the DOM's element with 'form-container' class
template: _.template($('#user-form').html()),
events: {
'submit': 'onFormSubmitted',
// validation logic could be added here
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
},
onFormSubmitted: function(e) {
e.preventDefault(); // we don't need to submit the form
// get form elements here and setting on model
// saving model at the end
var firstName = this.$('input[name="firstname"]').val();
var lastName = this.$('input[name="lastName"]').val();
this.model.set({firstname: firstName, lastname: lastName});
this.model.save(); // this will make POST request to your API
}
});
然后初始化你的view并传递User模型。
var userForm = new UserForm({model: new UserModel()});
我已经为你留下了模板的声明。
在使用 Backbone 时,有很多工作人员因跨源请求策略问题。实际上,这不是 Backbone 的事情。 Backbone 使用$.ajax 与 REST-full 资源进行交互。所以你只需要配置$.ajax。看here。