我对 Backbone 很陌生,我正在制作一个待办事项列表应用程序来学习基础知识。现在您可以添加一个任务,它会在待办事项列表中呈现。每个任务都有属性名称(字符串)和完成(布尔值)。我想这样做,以便在选中复选框(.toggle)时,将“完成”属性更改为 true。我还有一个“x”按钮(.destroy),单击该按钮应从数据库中删除任务。我无法让 markComplete 和 clear 事件正常工作。这是我的 tasks_index.js.coffee 视图:
class Backbonetodo.Views.TasksIndex extends Backbone.View
template: JST['tasks/index']
events:
'submit #new_task': 'createTask'
'click .toggle': 'markComplete'
'click .destroy': 'clear'
#I'd like this to change complete to true and put a line through the list item
markComplete: ->
@collection.set(complete:true)
initialize: ->
@collection.on('reset', @render, this)
@collection.on('add', @appendTask, this)
render: ->
$(@el).html(@template())
@collection.each(@appendTask)
this
appendTask: (task) ->
view = new Backbonetodo.Views.Task(model: task)
$('#tasks').append(view.render().el)
createTask: (task) ->
event.preventDefault()
attributes = name: $('#new_task_name').val()
@collection.create attributes,
wait: true
success: -> $('#new_task')[0].reset()
error: @handleError
handleError: (task, response) ->
if response.status == 422
errors = $.parseJSON(response.responseText).errors
for attribute, messages of errors
alert "#{attribute} #{message}" for message in messages
#This should remove the selected task from the database
clear: (task) ->
event.preventDefault()
@collection.remove()
这也可能有帮助。这是我的 task.js.coffee 视图:
class Backbonetodo.Views.Task extends Backbone.View
template: JST['tasks/task']
tagName: 'li'
render: ->
$(@el).html(@template(task: @model))
this