我有这个代码-
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
console.log @el 始终未定义。我不知道为什么,我认为我正在正确设置 this.el 吗?是否因为事件触发而调用渲染?
最佳答案
当您实例化您的 TableView
时,DOM 中没有 id="table1"
元素。例如,如果您在 DOM 中没有任何内容的情况下执行此操作:
class V extends Backbone.View
el: '#no-such-element'
render: => console.log @el
v = new V
v.render()
你会在控制台中得到一个undefined
。
演示:http://jsfiddle.net/ambiguous/ne39B/
如果您希望 Backbone 创建一个 id="table1"
元素,那么您需要使用不同的属性来告诉 Backbone 这样做; View#el
documentation状态:
this.el
is created from the view'stagName
,className
,id
andattributes
properties,
所以你有一些选择:
- 确保
#table1
在您创建 View 时位于 DOM 中。 - 在实例化时将
el
传递给 View :v = new TableView(el: some_dom_object)
。 - 使用
tagName
、className
、id
和attributes
View 属性获取Backbone构造合适的适合您的 DOM 元素。
此外,Backbone 不会为您将 View 的 el
添加到 DOM,即使 Backbone 构建 View 的 el
您也必须将其添加到 DOM自己。
关于javascript - 主干 View 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17479583/