我正在做一个教程,而我的问题就在我的代码的最底层,你实例化了一个新的App.Views.AddTask视图它无法正常工作,因为当你点击提交页面重新加载时e.preventDefault()不起作用。如果我只是在控制台中输入新的App.Views.AddTask,那么e.preventDefault()就会起作用,并且该页面不会提交导致其无法正常工作的原因。我的问题出在底部的adTaskView变量中。
(function() {
window.App = {
Models: {},
Collections: {},
Views: {}
};
window.template = function(id) {
return _.template($('#' + id).html());
}
App.Models.Task = Backbone.Model.extend({
validate: function(attrs) {
if(!$.trim(attrs.title)) {
return 'A task requires a valid title.'
}
}
});
App.Collections.Tasks = Backbone.Collection.extend({
model: App.Models.Task
})
App.Views.Tasks = Backbone.View.extend({
tagName: 'ul',
render: function() {
this.collection.each(this.addOne, this);
return this;
},
addOne: function(task) {
var taskView = new App.Views.Task({model: task});
this.$el.append(taskView.render().el);
}
})
App.Views.Task = Backbone.View.extend({
tagName: 'li',
template: template('taskTemplate'),
initialize: function() {
this.model.on('change', this.render, this);
this.model.on('destroy', this.remove, this);
},
events: {
'click .edit': 'editTask',
'click .delete': 'destroy'
},
editTask: function() {
var newTask = prompt('What would you likje to change the text to?', this.model.get('title'));
if(!$.trim(newTask)) return;
this.model.set('title', newTask);
},
destroy: function() {
this.model.destroy();
},
remove: function() {
this.$el.remove();
},
render: function() {
var template = this.template(this.model.toJSON());
this.$el.html( template );
return this;
}
})
window.tasksCollection = new App.Collections.Tasks([
{
title: 'Go tot the store',
priority: 4
},
{
title: 'Feed the dog',
priority: 2
},
]);
// PROBLEM WITH THIS PART
App.Views.AddTask = Backbone.View.extend({
el: '#addtask',
events: {
'submit': 'submit'
},
initialize: function() {
},
submit: function(e) {
e.preventDefault();
console.log('hit');
var newTaskTitle = $(e.currentTarget).find('input[type=text]').val();
var task = new App.Models.Task({ title: newTaskTitle});
this.collection.add(task);
}
});
var tasksView = new App.Views.Tasks({ collection: tasksCollection});
var addTaskView = new App.Views.AddTask({ collection: tasksCollection });
$(document).ready(function() {
$('.tasks').html(tasksView.render().el);
});
})();
形式:
<form action="" id="addtask">
<input type="text" name="task" id="task" />
<button type="submit">Add Task</button>
</form>
答案 0 :(得分:0)
看看这个:
events: {
'submit': 'submit'
},
您可以在页面上的submit
元素中添加事件。但你想要:
events: {
'button[type=submit]': 'submit'
},
或
events: {
'button': 'submit'
},
答案 1 :(得分:0)
submit
事件为时已晚,无法阻止提交。您应该将处理程序绑定到click
事件。
events: {
'click': 'submit'
},