Yepnope.js 和 RequireJS 提供類似的功能, 都是用來載入外部的 *.js 或 *.css。Yepnope.js 可以依條件而決定是否載入, 同時也可以確保我們要的執行順序, 感覺還不錯。
但 Yepnope.js 和 coffee-script.js 搭配時, 無法直接透過 Yepnope.js 載入 *.coffee 並執行; 而是在載入 coffee-script.js 後, 以 CoffeeScript.load() 分別載入 *.coffee 檔。
以下的範例又搭配 Backbone.js, 為了讓類別定義可以自由取用, 將類別名放在 window.myproj 物件下當做屬性。
<<< t03_yepnope.html ----------------------------------->>>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
</head>
<body>
<div id="buttons" mydata="shinder">
<button id="b1"> Button 1 </button>
<button> Button 2 </button>
<button> Button 3 </button>
</div>
<script type="text/javascript" src="js/yepnope.1.5.3-min.js"></script>
<script type="text/javascript">
var coffees = ['t03_yepnope2', 't03_yepnope1', 't03_yepnope3'];
yepnope([
{ load: "js/jquery-1.7.1.js" },
{ load: "js/underscore-1.3.1.js" },
{ test: !JSON, yep:"js/json2_min.js" },
{ load: "js/backbone.js" },
{
load: "js/coffee-script.js",
complete: function(){
for(var i=0; i<coffees.length; i++) {
CoffeeScript.load( coffees[i] + ".coffee");
}
}
}
]);
</script>
</body>
</html>
<<< t03_yepnope1.coffee ----------------------------------->>>
$ = jQuery
window.myproj ||= {}
$ ->
class myproj.MainView extends Backbone.View
el: 'body'
initialize: ->
buttons = new myproj.ButtonsView
console.log buttons.$el.attr('mydata')
<<< t03_yepnope2.coffee ----------------------------------->>>
$ = jQuery
window.myproj ||= {}
$ ->
class myproj.ButtonsView extends Backbone.View
el: '#buttons'
events:
'click': 'onClick'
'click #b1': 'b1Click'
'click button:eq(1)': 'b2Click'
'click button:nth-child(odd)': 'oddClick'
onClick: (event)->
# console.log event # jQuery.Event
console.log $(event.target).html()
b1Click: ->
console.log 'b1'
b2Click: ->
console.log 'b2'
oddClick: ->
console.log 'odd'
<<< t03_yepnope3.coffee ----------------------------------->>>
$ = jQuery
window.myproj ||= {}
$ ->
mainView = new myproj.MainView;
相關文章: Yepnope.js 和 CoffeeScript 拆檔 (續)
1 則留言:
看了 browser.coffee 的原始碼, CoffeeScript.load 走的是非同步模式(asynchronous)
https://github.com/jashkenas/coffee-script/blob/master/src/browser.coffee
張貼留言