with help of books and tutorials im trying to do my own Todo list app. My problem is that when you add ah todo my model should validate if the input come with some text before rendering. i created the validate methis but it doesnt work and i dont know how to track the error, i'll appreciate if you guys could help me finding my error
Model:
var Task = Backbone.Model.extend({
validate: function(attrs){
if(!attrs.title){
return "The task has no title";
}
}
});
var task = new Task;
Collection:
var Tasks = Backbone.Collection.extend({
model: Task
});
var tasks = new Tasks([
{
title: 'my task'
},
{
title: 'my task 1'
},
{
title: 'my task 2'
},
{
title: 'my task 3'
}
]);
Views:
var TaskView = Backbone.View.extend({
tagName: "li",
template: _.template( $('#task').html() ),
initialize: function(){
this.model.on("change", this.render, this);
},
render: function(){
var template = this.template( this.model.toJSON() );
this.$el.html( template );
return this;
},
events: {
'click .icon-checkbox': 'toggleState'
},
toggleState: function(e){
var $checkbox = $(e.target);
$checkbox.toggleClass('icon-checkbox-unchecked');
}
});
var TasksView = Backbone.View.extend({
el: '#tasks',
initialize: function(){
this.render();
this.collection.on('add', this.addOne, this);
},
render: function(){
this.collection.each(this.addOne, this);
return this;
},
addOne: function(task){
var taskView = new TaskView({ model: task });
this.$el.append( taskView.render().el );
}
});
var AddTask = Backbone.View.extend({
el: '#todos',
events:{
'click #add': 'addTask'
},
addTask: function(){
var taskTitle = $('#inputTask').val();
$('#inputTask').val("");
var task = new Task( {title: taskTitle} ); // create the task model
this.collection.add(task); //add the model to the collection
}
});
var tasksView = new TasksView( {collection: tasks} );
var addTask = new AddTask( {collection: tasks} );
Edit:
I just realized that the validate methos its on ly called when you set or save info in the model, but actually what i want to do is check when the user submit a todo that if it comes with text or ini order to create and render the model.