練習範例1
- test1.html
在HTML檔案中引入require.js並將data-main設為js資料夾中的common檔案,由於requireJS預設副檔名為js所以可以省略
<html> <head> <script data-main="js/common" src="js/require.js"></script> </head> <body> 123 </body> </html>
- js(Folder)
- common.js
require.config({ paths: { jquery: 'jquery-2.1.4.min', underscore: 'underscore', backbone: 'backbone' } }); require(['test1']);
- test1.js
define(function (require) { var $ = require('jquery'); var _ = require('underscore'); var backbone = require('backbone'); $(function(){ alert("a"); var JQv=$().jquery; var BKv=Backbone.VERSION; var Undv=_.VERSION; var myView = Backbone.View.extend({ el: $("body"), initialize: function () { this.showLoadinfo(JQv,Undv,BKv); }, showLoadinfo: function (JQv,BKv,Undv) { var hStr="<h1>載入測試</h1><ul id='mylist'>"; hStr+="<li>1. JQuery版本:"+JQv+"</li>"; hStr+="<li>2. Backbone版本:"+Undv+"</li>"; hStr+="<li>3. underscore版本:"+BKv+"</li>"; hStr+="</ul>"; this.$el.html(hStr); } }); var myLoadinfoView = new myView(); }); });
- common.js
結果:
載入測試
- 1. JQuery版本:2.1.4
- 2. Backbone版本:1.2.1
- 3. underscore版本:1.8.3
練習範例2
- test2.html
在HTML檔案中引入require.js並將data-main設為js資料夾中的test2檔案,由於requireJS預設副檔名為js所以可以省略
<html> <head> <script data-main="js/test2" src="js/require.js"></script> </head> <body> 123 </body> </html>
- js(Folder)
- common2.js
require.config({ paths: { jquery: 'jquery-2.1.4.min', underscore: 'underscore', backbone: 'backbone', myTestFunc: 'myTestFunc' } });
require(['test1']); - test2.js
require(['common2'], function (common){ require(['myTestFunc']); });
- myTestFunc.js
define(function (require) { var $ = require('jquery'); var _ = require('underscore'); var backbone = require('backbone'); $(function(){ alert("a"); var JQv=$().jquery; var BKv=Backbone.VERSION; var Undv=_.VERSION; var myView = Backbone.View.extend({ el: $("body"), initialize: function () { this.showLoadinfo(JQv,Undv,BKv); }, showLoadinfo: function (JQv,BKv,Undv) { var hStr="<h1>載入測試</h1><ul id='mylist'>"; hStr+="<li>1. JQuery版本:"+JQv+"</li>"; hStr+="<li>2. Backbone版本:"+Undv+"</li>"; hStr+="<li>3. underscore版本:"+BKv+"</li>"; hStr+="</ul>"; this.$el.html(hStr); } }); var myLoadinfoView = new myView(); }); });
- common2.js
結果:
載入測試
- 1. JQuery版本:2.1.4
- 2. Backbone版本:1.2.1
- 3. underscore版本:1.8.3
沒有留言:
張貼留言