问题
I have this code -
class TableManager
tables : {}
tableViews :{}
nextId : 0
rootEl : 'body'
addTable:(json,el)->
newTableModel = new TableModel(json,@nextId)
newTableModel
@tables[@nextId] = newTableModel
el = "#table1"
newView = new TableView({model : newTableModel, columns : json["Columns"], el : el, id : @nextId})
@tableViews[@nextId] = newView
newTableModel.renderModel()
@nextId++
class TableView extends Backbone.View
tableId : ''
columns : ''
thead : ''
tbody : ''
input : ''
rows : ''
inputId : ''
typingTimer : ''
doneTypingInterval : 2000
el : '#table1'
initialize:()->
@model.bind "render", @render
@tableId = "resultsTable#{@options.id}"
@inputId = "filterInput#{@options.id}"
@columns = @options.columns
render:()=>
console.log "EL"
console.log $(@el)
console.log @el
The console.log @el is always undefined. I don't know why, I'm setting this.el correctly I thought? Is it because render is being called as a result of an event firing?
回答1:
You don't have an id="table1"
element in the DOM when you instantiate your TableView
. For example, if you do this without anything in the DOM:
class V extends Backbone.View
el: '#no-such-element'
render: => console.log @el
v = new V
v.render()
you'll get an undefined
in the console.
Demo: http://jsfiddle.net/ambiguous/ne39B/
If you want Backbone to create an id="table1"
element then you'll need to use different properties to tell Backbone to do so; the View#el documentation states:
this.el
is created from the view'stagName
,className
,id
andattributes
properties,
So you have some options:
- Make sure
#table1
is in the DOM when you create the view. - Pass the
el
to the view when you instantiate it:v = new TableView(el: some_dom_object)
. - Use the
tagName
,className
,id
, andattributes
view attributes to get Backbone to construct the appropriate DOM element for you.
Also, Backbone won't add the view's el
to the DOM for you, even if Backbone builds the view's el
you'll have to add it to the DOM yourself.
来源:https://stackoverflow.com/questions/17479583/backbone-view-el-not-defined