I have a backbone IndexView which calls a TaskView for each ‘task’ model. I’d like to bind an event to the li element that wraps the taskview. So for example, the ‘className’ attribute is ‘task’, and I want to trigger an event on ‘.task’.
I can bind from the parent (IndexView) view, but I’d like access to information inside the clicked view, which I’m guessing means the event should be bound to the child TaskView(?)
(Also, DOM classes inside the actual tasks template can be accessed…just not the wrapping .task li)
Any ideas appreciated – code below.
CHILD VIEW
Backbonescaffolddemo.Views.Tasks ||= {}
class Backbonescaffolddemo.Views.Tasks.TaskView extends Backbone.View
template: JST["backbone/templates/tasks/task"]
tagName: "li"
className: "task"
events:
"click .task" : "demoMethod"
initialize: () ->
_.bindAll(this, 'demoMethod', 'render')
console.log @
#@showTask()
@el.id = 'sort_order_' + @model.get('id') if @model
destroy: () ->
@model.destroy()
this.remove()
return false
demoMethod: () ->
console.log 'Work dammit, work. Arghhh'
render: ->
$(@el).html(@template(@model.toJSON() ))
return this
PARENT VIEW
Backbonescaffolddemo.Views.Tasks ||= {}
class Backbonescaffolddemo.Views.Tasks.IndexView extends Backbone.View
template: JST["backbone/templates/tasks/index"]
id: "taskList"
events:
"keyup #searchTasks" : "searchTasks"
initialize: () ->
_.bindAll(this, 'addOne', 'sortable', 'task_id_from_element', 'addAll', 'searchTasks', 'updateSort', 'sortable', 'render')
@options.tasks.bind('reset', @addAll)
@options.tasks.bind('reset', @sortable)
@options.tasks.bind('add', @render)
@updateSort()
@sortable()
#...
addAll: () ->
@options.tasks.each(@addOne)
addOne: (task) ->
view = new Backbonescaffolddemo.Views.Tasks.TaskView({model: task})
$(@el).append(view.render().el)
render: ->
$(@el).html(@template(tasks: @options.tasks.toJSON() ))
@addAll()
return this
Ahh – found it. A straight-out “click” : “demoMethod” (with no specified DOM scope) does the job.