gpt4 book ai didi

javascript - CoffeeScript/Backbone/Marionette - 教程示例转换和范围界定问题

转载 作者:行者123 更新时间:2023-11-29 17:24:00 24 4
gpt4 key购买 nike

我正尝试在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com