저는 자습서를 진행하고 있습니다. 문제는 새 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>