0

我对 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
4

1 回答 1

0
markComplete: (event) ->
  # You need to get somehow specific task id
  # Example: id = $(event.currentTarget).data('id'), if you have the id in the DOM
  @collection.get(id).set(complete:true)

# You have here a parameter task which is actually event
clear: (task) ->
  event.preventDefault() # This is task :p
  # Same as before: get your task or task id
  # Example: 
  #  taskId = $(event.currentTarget).data('id')
  #  task = @collection.get(taskId)
  @collection.remove(task)

我的示例取决于您的模板。

建议:按照我使用的方式,尝试使用@$而不是$, 将元素范围限定为您的视图元素$

于 2013-05-04T22:38:23.590 回答