我正在尝试在 CoffeeScript 中创建此示例的基本版本:http://davidsulc.com/blog/2012/04/15/a-simple-backbone-marionette-tutorial/ 。所有依赖项都按照我编写它们的顺序(在正文中)声明为 .coffee 文件,并且 jQuery + Underscore + Backbone + Marionette 位于头部。
我有一个模型,thing.coffee
$ ->
console.log 'load model'
class Thing extends Backbone.Model
defaults:
myValue: null
initialize: ->
console.log 'new thing'
window.Thing = Thing
我的第一个问题是范围界定:如果我不声明 window.Thing
,下一个文件(Things
的集合)将无法找到模型 Thing
等等。我在那里做错了什么?
我有一个收藏,things.coffee
$ ->
console.log 'load collection'
class Things extends Backbone.Collection
model: Thing
window.Things = Things
我有一个 Marionette View ,thing_view.coffee
$ ->
console.log 'load composite model view'
ThingView = Backbone.Marionette.ItemView.extend(
template: '#template-thing'
tagName: 'tr'
)
window.ThingView = ThingView
我有一个 Marionette View ,things_view.coffee
$ ->
console.log 'load composite collection view'
ThingsView = Backbone.Marionette.CompositeView.extend(
tagName: 'table'
id: 'things'
template: '#template-things'
itemView: ThingView
appendHtml: (collectionView, itemView) ->
collectionView.$('tbody').append itemView.el
)
window.ThingsView = ThingsView
我有一个应用程序myapp.coffee
$ ->
console.log 'load app'
# Load default data
thingsCollection = new Things([
new Thing(myValue: 'uno'),
new Thing(myValue: 'dos')
])
data:
thingsCollection: thingsCollection
# Create application, specify default layouts
MyApp = new Backbone.Marionette.Application()
MyApp.addRegions singleRegion: '#content'
# On application init...
MyApp.addInitializer (data) ->
console.log 'Init application...'
thingsView = new ThingsView(collection: data.thingsCollection)
MyApp.singleRegion.show data.thingsView
# Start application
MyApp.start data
我的 html 文件如下所示:
<div id="content">
<script type="text/template" id="template-things">
<thead>
<tr class='header'>
<th>myValue</th>
</tr>
</thead>
<tbody>
</tbody>
</script>
<script type="text/template" id="template-thing">
<td><%= myValue %></td>
</script>
</div>
遵循console.log
:
load model
load collection
load composite model view
composite collection view
load app
Init application...
Uncaught TypeError: Cannot call method 'render' of undefined
所以,不用说我对发生的事情感到困惑 - 我确信这里有很多问题,所以请帮忙!
最佳答案
window.Thing
是 Coffeescript 避免全局命名空间污染的副产品。解决这个问题的惯用方法是 use an App
namespace .
仅在 DOM 加载时初始化类是 Backbone anti-pattern 。如果您为类命名,那么您只需确保以正确的顺序加载它们(项目 View 在 Collection View 之前),并且可以立即创建它们,而不是在页面加载后创建。
您能否告诉我们 Uncaught TypeError
发生在哪里?
关于javascript - CoffeeScript/Backbone/Marionette - 教程示例转换和范围界定问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10525379/