我是新手,backbone.js
我在表(HTML)中添加动态行,但是当我在保存按钮上打印表数据时它显示空数据,我的代码如下
(function($){
Backbone.sync = function(method, model, success, error){
success();
}
var Person = Backbone.Model.extend({
defaults: {
srNo:1,
name: ''
}
});
var ListPerson = Backbone.Collection.extend({
model: Person
});
var ItemView = Backbone.View.extend({
tagName: 'tr', // name of tag to be created
events: {
'click span#spanDelete': 'remove'
},
initialize: function(){
_.bindAll(this, 'render', 'unrender', 'remove');
this.model.bind('add', this.render);
this.model.bind('remove', this.unrender);
},
render: function(){
$(this.el).append("<td>"+this.model.get('srNo')+"</td><td><input type='text' id='txt1' value="+this.model.get('name')+"></td><td><span class='delete' id='spanDelete' style='cursor:pointer; color:red; font-family:sans-serif;'>[delete]</span></td>");
return this;
},
unrender: function(){
$(this.el).remove();
},
remove: function(){
this.model.destroy();
}
});
var ListView = Backbone.View.extend({
el: $('body'), // attaches `this.el` to an existing element.
initialize: function(){
_.bindAll(this, 'render', 'addItem', 'appendItem');
this.collection = new ListPerson();
this.collection.bind('add', this.appendItem);
this.counter = 0;
this.render();
},
events: {
'click button#btnAdd': 'addItem',
'click button#btnSave': 'saveData'
},
render: function(){
var self = this;
$(this.el).append("<button id='btnAdd'>Add list item</button>");
$(this.el).append("<table border=1 id='dtl1'></table>");
$(this.el).append("<button id='btnSave'>Save</button>");
_(this.collection.models).each(function(person){
self.appendItem(person);
}, this);
},
addItem: function(){
this.counter++;
var person = new Person();
person.set({
srNo: this.counter // modify item defaults
});
this.collection.add(person);
},
appendItem: function(item){
var itemView = new ItemView({
model: item
});
$('table', this.el).append(itemView.render().el);
},
saveData: function(){
var obj=this.collection.toJSON();
var str_json = JSON.stringify(obj);
alert(str_json);
}
});
var listView = new ListView();
})(jQuery);
名称不显示在输出中