Emberjs With Requirejs

這幾天survey了requirejs順便讓它與emberjs跑在一起,有些心得所以在這裡紀錄一下。

就如requirejs官方網站的介紹當使用requirejs來管理javascript module load後在index.html裡只要有一行script載入你最主要的javascript,在這裡是main.js

index.html
1
<script data-main="scripts/main" src="scripts/require.js"></script>

來看一下main.js

main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
require.config({
    baseURL: '/scripts/',
    'paths': {
        'jquery': 'libs/jquery.min',
        'handlebars':'libs/handlebars-1.0.rc.1',
        'ember':'libs/ember_0114',
        'text':'libs/text',
        'T':'templates'
    },
    shim : {
        'ember' : {
            deps: ['handlebars', 'jquery'],
            exports: 'Ember'
        }
    }
});

requirejs([
    'ember',
    'app',
    'route'
    'T/application.template'
],
function () {
   console.log("all loaded done");
});

require.config中baseURL是指javascript根目錄,我所有javascript都放在scripts/底下, scripts/libs/目錄底下則是放了third party js library,paths中可以命名短字串避免每次都要輸入很長的字串, shim是用來載入library如果不支援AMD使用,由於emberjs本身不支援AMD所以用shim載入。 檔案底部是requireJS的module定義,[]裡面描述你的dependency,function(){}代表當所有dependency module載入後要執行的code。 在這裡我載入ember,app,route以及T/application.template四個modules,在function()裡只是簡單地印一下log。

app.js
1
2
3
4
5
6
7
8
// var App = Ember.Application.create({});
define([
    'ember'
], function(Ember) {
  console.log("ember initial and callback");
  var App = window.App = Ember.Application.create({});
  return App;
});

app.js裡面寫當emberjs載入後建立我的App,這裡必須把App放進window.App不然在跑emberjs時會有錯誤。

application.template.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
define([
  'ember',
    'views/menubar.view'
], function(Ember) {
  Ember.TEMPLATES['application'] = Ember.Handlebars.compile(
  '\
     <h1>Hello Ember</h1>\
     <div>\
         { {view App.MenuBarView}}\
         <hr/>\
         { {outlet}}\
     </div>\
 '
  );
});

application.template裡面有兩個dependency(ember和menubar.view)。function裡面是comiple ember template。 在前面的app.js裡面如果沒有把App放進window.App話等程式run下去ember會報錯說找不到App.MenuBarView即使你的確有這個View存在。

menubar.view.js
1
2
3
4
5
6
7
8
9
10
define([
  'app',
  'text!T/menubar.template.html'
], function(App, template) {
  App.MenuBarView = Ember.View.extend({
      tagName:'div',
      classNames:['menubar']
  });
  Ember.TEMPLATES['menubar'] = Ember.Handlebars.compile(template);    
});

menubar.view.js裡面我利用text這個requirejs plugin載入外部的html進來ember compile。那如何得到載入進來的html呢?很簡單就 是只要在function裡面加入相對應的parameters,由於這個module有2個dependencies所以在function裡面有2個parameters。而template 很自然就是對應到讀進來的html。

Comments