Joh*_*ohn 11 javascript jquery serialization json backbone.js
我正在开发RESTful应用程序 - 我在服务器端使用Java,在前端使用Backbone.2将通过JSON进行通信.
我的应用程序有很多表单,我想:
我的问题:
我的代码到目前为止:
Javascript和Backbone
$(function(){
$.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;
};
//Model
var SignupForm = Backbone.Model.extend();
//View
var SignupView = Backbone.View.extend({
el: '.signupForm',
events: {
'click input.submit': 'getStatus'
},
getStatus: function(event){
var data = JSON.stringify($('form').serializeObject());
$('.test').html(data);
return false;
}
});
var signupForm = new SignupForm();
var signupView = new SignupView({
model: signupForm
});
});
Run Code Online (Sandbox Code Playgroud)
HTML
<div class="signupForm">
<form class"signup">
<label for="name" >Name:</label>
<input type="text" id="name" name="name" />
<label for="surname" >Surname:</label>
<input type="text" id="surname" name="surname" />
<input type="submit" value="submit" class="submit" />
</form>
<div class="test"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
我是Backbone的新手,很抱歉,如果这是微不足道的话.
我希望尽可能以最好的方式编写我的应用程序代码,所以请随时告诉我是否有更好的方法来执行此操作.
非常感谢.
Backbone 不会对您如何实现行为做出任何假设。它只提供一个干净的架构模式。因此,您实现表单序列化的方式似乎很好(类似于或改编自:Convert form data to JavaScript object with jQuery)
就持久性而言,您可以在单击提交按钮时设置模型的属性。
在您看来:
getStatus: function(event){
var data = JSON.stringify($('form').serializeObject());
this.model.set(data);
}
Run Code Online (Sandbox Code Playgroud)
在你的模型中:
initialize: function(){
//This will save attributes every time a change event is triggered.
this.bind("change", this.save);
}
Run Code Online (Sandbox Code Playgroud)