在 Backbone.js 上在线查找文档真的很容易,但很难找到关于如何在项目中设置 Backbone 并具有良好的类分离的教程或文档。大多数教程只会将所有代码转储到文档就绪函数中......并没有真正投入其中。
我正在尝试遵循此处找到的骨干命名空间模式(使用咖啡脚本而不是香草 js)http://ricostacruz.com/backbone-patterns/#namespace_convention
这是我的基本设置:
索引.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<link rel="stylesheet" type="text/css" href="css/jquery.mobile-1.2.0.css" />
<!--link rel="stylesheet" type="text/css" href="css/white-skateapp-theme.css" /-->
<link rel="stylesheet" type="text/css" href="css/jquery-mobile-overrides.css" />
<link rel="stylesheet" type="text/css" href="css/custom-icons.css" />
<title>Hello World</title>
</head>
<body>
<!-- SPOTS LIST -->
<div data-role="page" id="spots">
<div data-role="header">
<h1>Spots</h1>
<a href="#search" data-role="button" class="ui-btn-right" data-icon="search" data-corners="false">search</a>
</div><!-- /header -->
<div data-role="content">
spots list
</div><!-- /content -->
<!-- footer fixed bottom -->
<div data-role="footer" class="ui-bar" data-position="fixed">
<div data-role="navbar">
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#spots">Spots</a></li>
<li><a href="#me">Me</a></li>
<li><a href="#friends">Friends</a></li>
</ul>
</div>
<!-- /navbar -->
</div>
</div><!-- /page -->
<script type="text/javascript" src="cordova-2.1.0.js"></script>
<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.2.0.js"></script>
<script type="text/javascript" src="js/underscore.js"></script>
<script type="text/javascript" src="js/backbone.js"></script>
<!-- backbone -->
<!-- backbone views -->
<script type="text/javascript" src="js/app/views/spots_list.js"></script>
<!-- backbone app js file, not to be confused with phonegap app.whatever -->
<script type="text/javascript" src="js/app.js"></script>
<!-- initialize the phonegap app -->
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
应用程序.coffee
window.App =
Models: {}
Views: {}
Collections: {}
Routers: {}
init: ->
spotsList = new App.Views.SpotsList()
$ ->
console.log "init"
App.init()
spot_index.coffee
class App.Views.SpotsListView extends Backbone.View
el: $ 'body'
initialize: ->
console.log "initialize called"
目录和项目设置如下所示:
问题是,当 document ready 触发时,我收到此错误:
Uncaught ReferenceError: App is not defined
也得到这个错误:
Uncaught TypeError: Object #<Object> has no method 'init' app.js:20
(anonymous function) app.js:20
fire jquery-1.8.2.js:974
self.fireWith jquery-1.8.2.js:1082
jQuery.extend.ready jquery-1.8.2.js:406
DOMContentLoaded
(顺便说一句,这个项目是在 Phonegap、coffeescript、backbone.js 和 jQuery Mobile 中完成的)