在書籍和教程的幫助下,試圖做我自己的Todo列表應用程序。我的問題是,當你添加啊todo時,我的模型應該驗證輸入是否在渲染前帶有一些文本。我創建了驗證Methis Hotel酒店,但它不工作,我不知道如何追蹤錯誤,我會很感激,如果你們能幫助我找到我的錯誤使用Backbone.js驗證模型
型號:
var Task = Backbone.Model.extend({
validate: function(attrs){
if(!attrs.title){
return "The task has no title";
}
}
});
var task = new Task;
收藏:
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'
}
]);
瀏覽:
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});
編輯:
我剛剛意識到,當您在模型中設置或保存信息時,會調用驗證方法,但實際上我想要做的是檢查用戶何時提交待辦事項,如果它帶有文本或ini命令創建和渲染模型。
我剛剛意識到驗證methos當你設置或保存信息模型及其在立法院呼籲,但其實我想要做的是檢查,當用戶提交一個待辦事項,如果它帶有文本或ini命令來創建和渲染模型。 –