I’m trying to switch the tagName of a Backbone view based on a condition.
I initially thought I would be able to set a default tagName of say ‘div’ (I realize this is the default), then in the view’s initialize function, check for the condition and change the tagName but this unfortunately didn’t work.
Here is my view code (written in coffeescript):
class Test.Views.ListView extends Backbone.View
attributes: {"data-role": "listview"}
className: 'row'
tagName: 'div'
initialize: ->
if @options and @options.device == "mobile"
@template = "/app/templates/mobile/test/test.html"
@tagName = 'ul'
With this code, the tagName does not change, it always remains a div. While the template is switched correctly.
Any help would be appreciated. Cheers!
The view’s
elis set up beforeinitializeis called. From the fine manual:So all view instances always have an
eland in particular,elis created from the view’stagNamebeforeinitializeis called. You’re trying to change@tagNamein your constructor butelalready exists so it is too late for a simple@tagNamechange to have any effect.You can use
setElementto change the view’sel:Something like this:
You could also set
@tagName = 'ul'if you wanted but it won’t matter sincetagNameis only used when instantiating a view. Also,@optionsshould always be there so you don’t have to check it and since you’re using CoffeeScript, the accessor variant of the existential operator would be more idiomatic if you wanted to check it anyway:Demo: http://jsfiddle.net/ambiguous/j4mSu/1/