Backbone.js 从多个视图提交表单的主干
我有一个主视图App.MainView表视图,一个App.TaskView行视图,并使用主干表单添加和编辑记录。这是我的密码:Backbone.js 从多个视图提交表单的主干,backbone.js,backbone-forms,Backbone.js,Backbone Forms,我有一个主视图App.MainView表视图,一个App.TaskView行视图,并使用主干表单添加和编辑记录。这是我的密码: App.MainView = Backbone.View.extend({ template: $("#home-template").html(), initialize: function() { _.bindAll(this, 'render'); thi
App.MainView = Backbone.View.extend({
template: $("#home-template").html(),
initialize: function() {
_.bindAll(this, 'render');
this.listenTo(tasks, 'add change', this.addOne);
this.subViews = [];
},
addOne: function(model) {
var view = new App.TaskView({model: model});
this.$('tbody').append(view.render().el);
},
render: function() {
var template = _.template(this.template);
this.$el.append(template);
//this.$el.find("#filter").append(this.createSelect());
var self = this;
this.collection.fetch({
wait: true,
success: function(model, response) {
var TasksLen = model.length;
for (var i = 0; i < TasksLen; i++) {
var taskView = new App.TaskView({
model: model.models[i]
});
//self.subViews.push(taskView);
$('#record-list-table', this.el).append(taskView.render().el);
}
}
});
},
Now my TaskView:
App.TaskView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#record-template').html()),
initialize: function() {
var self = this;
},
events: {
"click .edit": "editrecord",
},
render: function() {
this.$el.html(this.template(this.model.toJSON()))
return this;
},
editrecord: function() {
form.setValue(this.model.toJSON());
}
and my Form and submit button
var form = new Backbone.Form({
model: task
});
window.form = form;
$('#form').html(form.render().el);
$('#submit-btn').click(function() {
var data = form.getValue();
form.commit();
task.save(data, {wait: true,
success: function(task, response) {
tasks.add(task);
}
});
Templates:
<script type="text/template" id="home-template">
<table id="recordtable">
<input type='reset' id="reset-btn" onclick="reset()" class="add-new" value='' name='reset' /></table></script>
<script type="text/template" id="record-template">
<td id="edit-name" class="edit"> <%- name %></td>
<td class="edit date" class="edit"> <%- due_date %></td>
</script>
我有两个问题:
在模型更改时,它添加另一个模型,但它执行put请求并在数据库中更新,但在前端主干上,它在表中添加一个新行,而不是更新前一行。但在页面刷新后,它会显示正确的数据。看起来更改事件存在一些问题
我想创建到任务(即任务/id)的直接路由,并想在表中突出显示该任务并在表单中编辑它。现在我可以在表单中单击编辑任何模型,但我也希望有直接路线
我想现在我发现了你代码的问题。你在干什么
tasks.add(task);
模型保存的成功方法。但我认为你需要重新安排任务。
1.您可以在taskview中绑定更改事件,以便它使用更新的值呈现任务。
2.您可以像这样在taskview中添加函数
refresh: function(){
this.render();
}
您可以在找到model.save success后调用此函数。我尝试过这样做,但看起来它将添加一个函数,而不是在更改时进行渲染。我认为这就是原因。this.listenTotasks,'addchange',this.addOne;如果我错了,请纠正我,因为我在成功保存后添加了:functiontask,response{var taskView=new App.taskView;taskView.refresh;}和taskView具有刷新函数refresh:function{this.render;},我收到错误,无法调用未定义this.model的方法“toJSON”。我怎样才能通过模型。你们需要像这样通过模型。var taskView=newapp.taskView{model:yourModel};是的,我正在传递我的模型,但它在更新时呈现新模型,看起来它没有关闭以前的视图