Is it ok to assign the @template() to an @el like this:
someview.js.coffee
class SomeView extends Backbone.View
template: JST["app/templates/sometemplate"]
events:
'click' : 'onClick'
initialize: ->
render: ->
@el = @template()
onClick: ->
#do something
index.js.coffee
class IndexView extends Backbone.View
initialize: ->
@collection.on('reset', @render, this)
render: ->
$(@el).html('')
for m in @collection.models
view = new App.Views.SomeView(model: m)
$(@el).append(view.render().el)
sometemplate.jst.hamlc
.someview_template
.stuff_inside
The situation I'm in, the SomeView class is being wrapped with a div and it's making me lose the click event I want assigned directly on the '.someview_template' element. The way I can think to solve this is by reseting the @el = @template()... is that possible or the right way to do this?
Is it the case that the @el of Backbone.View should always be the containing div, and the template should be only the elements contained within that div? Seems like it would be more basic if @el is automatically set to the root node found in the @template(). Should I just let the sometemplate.jst.hamlc contain only ".stuff_inside", then in SomeView set $(@el).addClass('someview_template'), that way I can be sure the events are assigned to that element?
Thanks!
No, that's not okay for a couple reasons:
@el
so none of your events will work. @$el
won't match @el
anymore. If you want to replace the @el
, use @setElement
:
setElement
view.setElement(element)
If you'd like to apply a Backbone view to a different DOM element, use setElement , which will also create the cached
$el
reference and move the view's delegated events from the old element to the new one.
You probably want something more like this:
render: ->
@setElement(@template())
@
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.