我对Backbone很陌生,我正在制作一个待办事项列表应用程序来学习基础知识。现在你可以添加一个任务,它会呈现在待办事项列表中。每个任务都有属性name(字符串)和complete(布尔值)。我想这样做,当复选框(.toggle)被选中时,'complete'属性被更改为true。我也有一个"x"按钮(.destroy),当点击应该从数据库中删除任务。我在获得markComplete和clear事件正确工作时遇到了麻烦。这是我的tasks_index.js。咖啡观点:
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
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)
我的例子取决于你的模板。
建议:尝试使用@$
而不是$
,以范围元素到您的视图的元素,顺便说一下,我使用$