加载中...

第十五章 引入requirejs


前面花了四章的时间完成了项目( wechat )的开发,并且也放到了线上。这篇来说说模块化的事情。

15.1 模块化的概念

对于通常的网站来说,一般我们不会把所有的js都写到一个文件中,因为当一个文件中的代码行数太多的话会导致维护性变差,因此我们常常会根据业务(页面)来组织js文件,比如全站都用到的功能,我就写一个base.js,只是在首页会用到的功能,就写一个index.js。这样的话我更改首页的逻辑只需要更改index.js文件,不需要考虑太多的不相关业务逻辑。当然还有很重要的一点是按需加载,在非index.js页面我就不需要引入index.js。

那么对于单页应用(SPA)来说要怎么做呢,只有一个页面,按照传统的写法,即便是分开多个文件来写,也得全部放到标签中,由浏览器统一加载。如果你有后端开发经验的话,你会意识到,是不是我们可以像写后端程序(比如Python)那样,定义不同的包、模块。在另外的模块中按需加载(import)呢?

答案当然是可以。

在前端也有模块化这样的规范,不过是有两套:AMD和CMD。关于这俩规范的对比可以参考知乎上的问答 AMD 和 CMD 的区别有哪些 。

按照AMD和CMD实现的两个可以用来做模块化的是库分别是:require.js和sea.js。从本章的题目可以知道我们这里主要把require.js引入我们的项目。 对于这两库我都做了一个简单的Demo,再看下面长篇代码之前,可以先感受下: require.js Demo 和 sea.js Demo 。

15.2 简单使用require.js

要使用require.js其实非常简单,主要有三个部分:1. 页面引入require.js;2. 定义模块;3. 加载模块。我们以上面提到我做的那个demo为例:

首先 - 页面引入

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>the5fire.com-backbone.js-Hello World</title>
  5. </head>
  6. <body>
  7. <button id="check">新手报到- requirejs版</button>
  8. <ul id="world-list">
  9. </ul>
  10. <a href="http://www.the5fire.com">更多教程</a>
  11. <script data-main="static/main.js" src="static/lib/require.js"></script>
  12. </body>
  13. </html>

上面的script的data-main定义了入口文件,我们把配置项也放到了入口文件中。 来看下入口文件:

  1. require.config({
  2. baseUrl: 'static/',
  3. shim: {
  4. underscore: {
  5. exports: '_'
  6. },
  7. },
  8. paths: {
  9. jquery: 'lib/jquery',
  10. underscore: 'lib/underscore',
  11. backbone: 'lib/backbone'
  12. }
  13. });
  14. require(['jquery', 'backbone', 'js/app'], function($, Backbone, AppView) {
  15. var appView = new AppView();
  16. });

上面baseUrl部分指明了所有要加载模块的根路径,shim是指那些非AMD规范的库,paths相当于你js文件的别名,方便引入。

后面的require就是入口了,加载完main.js后会执行这部分代码,这部分代码的意思是,加载 jquery 、 backbone 、js/app (这个也可通过paths来定义别名),并把加载的内容传递到后面的function的参数中。o

来看看js/app的定义。

定义模块

  1. // app.js
  2. define(['jquery', 'backbone'], function($, Backbone) {
  3. var AppView = Backbone.View.extend({
  4. // blabla..bla
  5. });
  6. return AppView;
  7. });
  8. // 或者这种方式
  9. define(function(require, exports, module) {
  10. var $ = require('jquery');
  11. var Backbone = require('backbone');
  12. var AppView = Backbone.View.extend({
  13. // blabla..bla
  14. });
  15. return AppView;
  16. });

这两种方式均可,最后需要返回你想暴露外面的对象。这个对象(AppView)会在其他模块中 require('js/app') 时加载,就像上面一样。

15.3 拆分文件

上一篇中我们写了一个很长的chat.js的文件,这个文件包含了所有的业务逻辑。这里我们就一步步来把这个文件按照require.js的定义拆分成模块。

上一篇是把chat.js文件分开来讲的,这里先来感受下整体代码:

  1. $(function(){
  2. var User = Backbone.Model.extend({
  3. urlRoot: '/user',
  4. });
  5. var Topic = Backbone.Model.extend({
  6. urlRoot: '/topic',
  7. });
  8. var Message = Backbone.Model.extend({
  9. urlRoot: '/message',
  10. });
  11. var Topics = Backbone.Collection.extend({
  12. url: '/topic',
  13. model: Topic,
  14. });
  15. var Messages = Backbone.Collection.extend({
  16. url: '/message',
  17. model: Message,
  18. });
  19. var topics = new Topics;
  20. var TopicView = Backbone.View.extend({
  21. tagName: "div class='column'",
  22. templ: _.template($('#topic-template').html()),
  23. // 渲染列表页模板
  24. render: function() {
  25. $(this.el).html(this.templ(this.model.toJSON()));
  26. return this;
  27. },
  28. });
  29. var MessageView = Backbone.View.extend({
  30. tagName: "div class='comment'",
  31. templ: _.template($('#message-template').html()),
  32. // 渲染列表页模板
  33. render: function() {
  34. $(this.el).html(this.templ(this.model.toJSON()));
  35. return this;
  36. },
  37. });
  38. var UserView = Backbone.View.extend({
  39. el: "#user_info",
  40. username: $('#username'),
  41. show: function(username) {
  42. this.username.html(username);
  43. this.$el.show();
  44. },
  45. });
  46. var AppView = Backbone.View.extend({
  47. el: "#main",
  48. topic_list: $("#topic_list"),
  49. topic_section: $("#topic_section"),
  50. message_section: $("#message_section"),
  51. message_list: $("#message_list"),
  52. message_head: $("#message_head"),
  53. events: {
  54. 'click .submit': 'saveMessage',
  55. 'click .submit_topic': 'saveTopic',
  56. 'keypress #comment': 'saveMessageEvent',
  57. },
  58. initialize: function() {
  59. _.bindAll(this, 'addTopic', 'addMessage');
  60. topics.bind('add', this.addTopic);
  61. // 定义消息列表池,每个topic有自己的message collection
  62. // 这样保证每个主题下得消息不冲突
  63. this.message_pool = {};
  64. this.message_list_div = document.getElementById('message_list');
  65. },
  66. addTopic: function(topic) {
  67. var view = new TopicView({model: topic});
  68. this.topic_list.append(view.render().el);
  69. },
  70. addMessage: function(message) {
  71. var view = new MessageView({model: message});
  72. this.message_list.append(view.render().el);
  73. },
  74. saveMessageEvent: function(evt) {
  75. if (evt.keyCode == 13) {
  76. this.saveMessage(evt);
  77. }
  78. },
  79. saveMessage: function(evt) {
  80. var comment_box = $('#comment')
  81. var content = comment_box.val();
  82. if (content == '') {
  83. alert('内容不能为空');
  84. return false;
  85. }
  86. var topic_id = comment_box.attr('topic_id');
  87. var message = new Message({
  88. content: content,
  89. topic_id: topic_id,
  90. });
  91. self = this;
  92. var messages = this.message_pool[topic_id];
  93. message.save(null, {
  94. success: function(model, response, options){
  95. comment_box.val('');
  96. // 重新获取,看服务器端是否有更新
  97. // 比较丑陋的更新机制
  98. messages.fetch({
  99. data: {topic_id: topic_id},
  100. success: function(){
  101. self.message_list.scrollTop(self.message_list_div.scrollHeight);
  102. messages.add(response);
  103. },
  104. });
  105. },
  106. });
  107. },
  108. saveTopic: function(evt) {
  109. var topic_title = $('#topic_title');
  110. if (topic_title.val() == '') {
  111. alert('主题不能为空!');
  112. return false
  113. }
  114. var topic = new Topic({
  115. title: topic_title.val(),
  116. });
  117. self = this;
  118. topic.save(null, {
  119. success: function(model, response, options){
  120. topics.add(response);
  121. topic_title.val('');
  122. },
  123. });
  124. },
  125. showTopic: function(){
  126. topics.fetch();
  127. this.topic_section.show();
  128. this.message_section.hide();
  129. this.message_list.html('');
  130. },
  131. initMessage: function(topic_id) {
  132. var messages = new Messages;
  133. messages.bind('add', this.addMessage);
  134. this.message_pool[topic_id] = messages;
  135. },
  136. showMessage: function(topic_id) {
  137. this.initMessage(topic_id);
  138. this.message_section.show();
  139. this.topic_section.hide();
  140. this.showMessageHead(topic_id);
  141. $('#comment').attr('topic_id', topic_id);
  142. var messages = this.message_pool[topic_id];
  143. messages.fetch({
  144. data: {topic_id: topic_id},
  145. success: function(resp) {
  146. self.message_list.scrollTop(self.message_list_div.scrollHeight)
  147. }
  148. });
  149. },
  150. showMessageHead: function(topic_id) {
  151. var topic = new Topic({id: topic_id});
  152. self = this;
  153. topic.fetch({
  154. success: function(resp, model, options){
  155. self.message_head.html(model.title);
  156. }
  157. });
  158. },
  159. });
  160. var LoginView = Backbone.View.extend({
  161. el: "#login",
  162. wrapper: $('#wrapper'),
  163. events: {
  164. 'keypress #login_pwd': 'loginEvent',
  165. 'click .login_submit': 'login',
  166. 'keypress #reg_pwd_repeat': 'registeEvent',
  167. 'click .registe_submit': 'registe',
  168. },
  169. hide: function() {
  170. this.wrapper.hide();
  171. },
  172. show: function() {
  173. this.wrapper.show();
  174. },
  175. loginEvent: function(evt) {
  176. if (evt.keyCode == 13) {
  177. this.login(evt);
  178. }
  179. },
  180. login: function(evt){
  181. var username_input = $('#login_username');
  182. var pwd_input = $('#login_pwd');
  183. var u = new User({
  184. username: username_input.val(),
  185. password: pwd_input.val(),
  186. });
  187. u.save(null, {
  188. url: '/login',
  189. success: function(model, resp, options){
  190. g_user = resp;
  191. // 跳转到index
  192. appRouter.navigate('index', {trigger: true});
  193. }
  194. });
  195. },
  196. registeEvent: function(evt) {
  197. if (evt.keyCode == 13) {
  198. this.registe(evt);
  199. }
  200. },
  201. registe: function(evt){
  202. var reg_username_input = $('#reg_username');
  203. var reg_pwd_input = $('#reg_pwd');
  204. var reg_pwd_repeat_input = $('#reg_pwd_repeat');
  205. var u = new User({
  206. username: reg_username_input.val(),
  207. password: reg_pwd_input.val(),
  208. password_repeat: reg_pwd_repeat_input.val(),
  209. });
  210. u.save(null, {
  211. success: function(model, resp, options){
  212. g_user = resp;
  213. // 跳转到index
  214. appRouter.navigate('index', {trigger: true});
  215. }
  216. });
  217. },
  218. });
  219. var AppRouter = Backbone.Router.extend({
  220. routes: {
  221. "login": "login",
  222. "index": "index",
  223. "topic/:id" : "topic",
  224. },
  225. initialize: function(){
  226. // 初始化项目, 显示首页
  227. this.appView = new AppView();
  228. this.loginView = new LoginView();
  229. this.userView = new UserView();
  230. this.indexFlag = false;
  231. },
  232. login: function(){
  233. this.loginView.show();
  234. },
  235. index: function(){
  236. if (g_user && g_user.id != undefined) {
  237. this.appView.showTopic();
  238. this.userView.show(g_user.username);
  239. this.loginView.hide();
  240. this.indexFlag = true; // 标志已经到达主页了
  241. }
  242. },
  243. topic: function(topic_id) {
  244. if (g_user && g_user.id != undefined) {
  245. this.appView.showMessage(topic_id);
  246. this.userView.show(g_user.username);
  247. this.loginView.hide();
  248. this.indexFlag = true; // 标志已经到达主页了
  249. }
  250. },
  251. });
  252. var appRouter = new AppRouter();
  253. var g_user = new User;
  254. g_user.fetch({
  255. success: function(model, resp, options){
  256. g_user = resp;
  257. Backbone.history.start({pustState: true});
  258. if(g_user === null || g_user.id === undefined) {
  259. // 跳转到登录页面
  260. appRouter.navigate('login', {trigger: true});
  261. } else if (appRouter.indexFlag == false){
  262. // 跳转到首页
  263. appRouter.navigate('index', {trigger: true});
  264. }
  265. },
  266. }); // 获取当前用户
  267. });

上面三百多行的代码其实只是做了最基本的实现,按照上篇文章的介绍,我们根据User,Topic,Message,AppView,AppRouter来拆分。当然你也可以通过类似后端的常用的结构:Model, View,Router来拆分。

User的拆分

这个模块我打算定义用户相关的所有内容,包括数据获取,页面渲染,还有登录状态,于是有了这个代码:

  1. // user.js
  2. define(function(require, exports, module) {
  3. var $ = require('jquery');
  4. var Backbone = require('backbone');
  5. var _ = require('underscore');
  6. var User = Backbone.Model.extend({
  7. urlRoot: '/user',
  8. });
  9. var LoginView = Backbone.View.extend({
  10. el: "#login",
  11. wrapper: $('#wrapper'),
  12. initialize: function(appRouter) {
  13. this.appRouter = appRouter;
  14. },
  15. events: {
  16. 'keypress #login_pwd': 'loginEvent',
  17. 'click .login_submit': 'login',
  18. 'keypress #reg_pwd_repeat': 'registeEvent',
  19. 'click .registe_submit': 'registe',
  20. },
  21. hide: function() {
  22. this.wrapper.hide();
  23. },
  24. show: function() {
  25. this.wrapper.show();
  26. },
  27. loginEvent: function(evt) {
  28. if (evt.keyCode == 13) {
  29. this.login(evt);
  30. }
  31. },
  32. login: function(evt){
  33. var username_input = $('#login_username');
  34. var pwd_input = $('#login_pwd');
  35. var u = new User({
  36. username: username_input.val(),
  37. password: pwd_input.val(),
  38. });
  39. var self = this;
  40. u.save(null, {
  41. url: '/login',
  42. success: function(model, resp, options){
  43. self.appRouter.g_user = resp;
  44. // 跳转到index
  45. self.appRouter.navigate('index', {trigger: true});
  46. }
  47. });
  48. },
  49. registeEvent: function(evt) {
  50. if (evt.keyCode == 13) {
  51. this.registe(evt);
  52. }
  53. },
  54. registe: function(evt){
  55. var reg_username_input = $('#reg_username');
  56. var reg_pwd_input = $('#reg_pwd');
  57. var reg_pwd_repeat_input = $('#reg_pwd_repeat');
  58. var u = new User({
  59. username: reg_username_input.val(),
  60. password: reg_pwd_input.val(),
  61. password_repeat: reg_pwd_repeat_input.val(),
  62. });
  63. var self = this;
  64. u.save(null, {
  65. success: function(model, resp, options){
  66. self.appRouter.g_user = resp;
  67. // 跳转到index
  68. self.appRouter.navigate('index', {trigger: true});
  69. }
  70. });
  71. },
  72. });
  73. var UserView = Backbone.View.extend({
  74. el: "#user_info",
  75. username: $('#username'),
  76. show: function(username) {
  77. this.username.html(username);
  78. this.$el.show();
  79. },
  80. });
  81. module.exports = {
  82. "User": User,
  83. "UserView": UserView,
  84. "LoginView": LoginView,
  85. };
  86. });

通过define的形式定义了User这个模块,最后通过module.exports暴露给外面User,UserView和LoginView。

Topic模块

同User一样,我们在这个模块定义Topic的Model、Collection和View,来完成topic数据的获取也最终渲染。

  1. //topic.js
  2. define(function(require, exports, module) {
  3. var $ = require('jquery');
  4. var Backbone = require('backbone');
  5. var _ = require('underscore');
  6. var Topic = Backbone.Model.extend({
  7. urlRoot: '/topic',
  8. });
  9. var Topics = Backbone.Collection.extend({
  10. url: '/topic',
  11. model: Topic,
  12. });
  13. var TopicView = Backbone.View.extend({
  14. tagName: "div class='column'",
  15. templ: _.template($('#topic-template').html()),
  16. // 渲染列表页模板
  17. render: function() {
  18. $(this.el).html(this.templ(this.model.toJSON()));
  19. return this;
  20. },
  21. });
  22. module.exports = {
  23. "Topic": Topic,
  24. "Topics": Topics,
  25. "TopicView": TopicView,
  26. }
  27. });

一样的,这个模块也对外暴露了Topic、Topics、TopicView的内容。

message模块

  1. //message.js
  2. define(function(require, exports, module) {
  3. var $ = require('jquery');
  4. var Backbone = require('backbone');
  5. var _ = require('underscore');
  6. var Message = Backbone.Model.extend({
  7. urlRoot: '/message',
  8. });
  9. var Messages = Backbone.Collection.extend({
  10. url: '/message',
  11. model: Message,
  12. });
  13. var MessageView = Backbone.View.extend({
  14. tagName: "div class='comment'",
  15. templ: _.template($('#message-template').html()),
  16. // 渲染列表页模板
  17. render: function() {
  18. $(this.el).html(this.templ(this.model.toJSON()));
  19. return this;
  20. },
  21. });
  22. module.exports = {
  23. "Messages": Messages,
  24. "Message": Message,
  25. "MessageView": MessageView,
  26. }
  27. });

最后也是对外暴露了Message、Messages和MessageView数据。

AppView模块

上面定义的都是些基础模块,这个模块我们之前也说过,可以称为“管家View”,因为它是专门用来管理其他模块的。

  1. //appview.js
  2. define(function(require, exports, module) {
  3. var $ = require('jquery');
  4. var _ = require('underscore');
  5. var Backbone = require('backbone');
  6. var TopicModule = require('topic');
  7. var MessageModule = require('message');
  8. var Topics = TopicModule.Topics;
  9. var TopicView = TopicModule.TopicView;
  10. var Topic = TopicModule.Topic;
  11. var Message = MessageModule.Message;
  12. var Messages = MessageModule.Messages;
  13. var MessageView = MessageModule.MessageView;
  14. var topics = new Topics();
  15. var AppView = Backbone.View.extend({
  16. el: "#main",
  17. topic_list: $("#topic_list"),
  18. topic_section: $("#topic_section"),
  19. message_section: $("#message_section"),
  20. message_list: $("#message_list"),
  21. message_head: $("#message_head"),
  22. events: {
  23. 'click .submit': 'saveMessage',
  24. 'click .submit_topic': 'saveTopic',
  25. 'keypress #comment': 'saveMessageEvent',
  26. },
  27. initialize: function() {
  28. _.bindAll(this, 'addTopic', 'addMessage');
  29. topics.bind('add', this.addTopic);
  30. // 定义消息列表池,每个topic有自己的message collection
  31. // 这样保证每个主题下得消息不冲突
  32. this.message_pool = {};
  33. this.message_list_div = document.getElementById('message_list');
  34. },
  35. addTopic: function(topic) {
  36. var view = new TopicView({model: topic});
  37. this.topic_list.append(view.render().el);
  38. },
  39. addMessage: function(message) {
  40. var view = new MessageView({model: message});
  41. this.message_list.append(view.render().el);
  42. self.message_list.scrollTop(self.message_list_div.scrollHeight);
  43. },
  44. saveMessageEvent: function(evt) {
  45. if (evt.keyCode == 13) {
  46. this.saveMessage(evt);
  47. }
  48. },
  49. saveMessage: function(evt) {
  50. var comment_box = $('#comment')
  51. var content = comment_box.val();
  52. if (content == '') {
  53. alert('内容不能为空');
  54. return false;
  55. }
  56. var topic_id = comment_box.attr('topic_id');
  57. var message = new Message({
  58. content: content,
  59. topic_id: topic_id,
  60. });
  61. var messages = this.message_pool[topic_id];
  62. message.save(null, {
  63. success: function(model, response, options){
  64. comment_box.val('');
  65. // 重新获取,看服务器端是否有更新
  66. // 比较丑陋的更新机制
  67. messages.fetch({
  68. data: {topic_id: topic_id},
  69. success: function(){
  70. self.message_list.scrollTop(self.message_list_div.scrollHeight);
  71. messages.add(response);
  72. },
  73. });
  74. },
  75. });
  76. },
  77. saveTopic: function(evt) {
  78. var topic_title = $('#topic_title');
  79. if (topic_title.val() == '') {
  80. alert('主题不能为空!');
  81. return false
  82. }
  83. var topic = new Topic({
  84. title: topic_title.val(),
  85. });
  86. self = this;
  87. topic.save(null, {
  88. success: function(model, response, options){
  89. topics.add(response);
  90. topic_title.val('');
  91. },
  92. });
  93. },
  94. showTopic: function(){
  95. topics.fetch();
  96. this.topic_section.show();
  97. this.message_section.hide();
  98. this.message_list.html('');
  99. this.goOut()
  100. },
  101. initMessage: function(topic_id) {
  102. var messages = new Messages;
  103. messages.bind('add', this.addMessage);
  104. this.message_pool[topic_id] = messages;
  105. },
  106. showMessage: function(topic_id) {
  107. this.initMessage(topic_id);
  108. this.message_section.show();
  109. this.topic_section.hide();
  110. this.showMessageHead(topic_id);
  111. $('#comment').attr('topic_id', topic_id);
  112. var messages = this.message_pool[topic_id];
  113. messages.fetch({
  114. data: {topic_id: topic_id},
  115. success: function(resp) {
  116. self.message_list.scrollTop(self.message_list_div.scrollHeight)
  117. }
  118. });
  119. },
  120. showMessageHead: function(topic_id) {
  121. var topic = new Topic({id: topic_id});
  122. self = this;
  123. topic.fetch({
  124. success: function(resp, model, options){
  125. self.message_head.html(model.title);
  126. }
  127. });
  128. },
  129. });
  130. return AppView;
  131. });

不同于上面三个基础模块,这个模块只需要对外暴露AppView即可(貌似也就只有这一个东西)。

AppRouter模块

下面就是用来做路由的AppRouter模块,这里只是定义了AppRouter,没有做初始化的操作,初始化的操作我们放到app.js这个模块中,app.js也是项目运行的主模块。

  1. // approuter.js
  2. define(function(require, exports, module) {
  3. var $ = require('jquery');
  4. var _ = require('underscore');
  5. var Backbone = require('backbone');
  6. var AppView = require('appview');
  7. var UserModule = require('user');
  8. var LoginView = UserModule.LoginView;
  9. var UserView = UserModule.UserView;
  10. var AppRouter = Backbone.Router.extend({
  11. routes: {
  12. "login": "login",
  13. "index": "index",
  14. "topic/:id" : "topic",
  15. },
  16. initialize: function(g_user){
  17. // 设置全局用户
  18. this.g_user = g_user;
  19. // 初始化项目, 显示首页
  20. this.appView = new AppView();
  21. this.loginView = new LoginView(this);
  22. this.userView = new UserView();
  23. this.indexFlag = false;
  24. },
  25. login: function(){
  26. this.loginView.show();
  27. },
  28. index: function(){
  29. if (this.g_user && this.g_user.id != undefined) {
  30. this.appView.showTopic();
  31. this.userView.show(this.g_user.username);
  32. this.loginView.hide();
  33. this.indexFlag = true; // 标志已经到达主页了
  34. }
  35. },
  36. topic: function(topic_id) {
  37. if (this.g_user && this.g_user.id != undefined) {
  38. this.appView.showMessage(topic_id);
  39. this.userView.show(this.g_user.username);
  40. this.loginView.hide();
  41. this.indexFlag = true; // 标志已经到达主页了
  42. }
  43. },
  44. });
  45. return AppRouter;
  46. });

同样,对外暴露AppRouter,主要供app.js这个主模块使用。

app模块

最后,让我们来看下所有js的入口:

  1. // app.js
  2. define(function(require) {
  3. var $ = require('jquery');
  4. var _ = require('underscore');
  5. var Backbone = require('backbone');
  6. var AppRouter = require('approuter');
  7. var UserModule = require('user');
  8. var User = UserModule.User;
  9. var g_user = new User();
  10. var appRouter = new AppRouter(g_user);
  11. g_user.fetch({
  12. success: function(model, resp, options){
  13. g_user = resp;
  14. Backbone.history.start({pustState: true});
  15. if(g_user === null || g_user.id === undefined) {
  16. // 跳转到登录页面
  17. appRouter.navigate('login', {trigger: true});
  18. } else if (appRouter.indexFlag == false){
  19. // 跳转到首页
  20. appRouter.navigate('index', {trigger: true});
  21. }
  22. },
  23. }); // 获取当前用户
  24. });

这个模块中,我们通过require引入Approuter,引入User模块。需要注意的是,不同于之前一个文件中所有的模块可以共享对象的实例(如:g_user, appRouter),这里需要通过参数传递的方式把这个各个模块都需要的对象传递过去。同时AppRouter和User也是整个页面生存期的唯一实例。因此我们把User对象作为AppRouter的一个属性。在上面的AppRouter定义中,我们又吧AppRouter的实例传递到了LoginView中,因为LoginView需要对url进行变换。

总结

好了,我们总结下模块拆分的结构,还是来看下项目中js的文件结构:

  1. └── js
  2. ├── app.js
  3. ├── approuter.js
  4. ├── appview.js
  5. ├── backbone.js
  6. ├── jquery.js
  7. ├── json2.js
  8. ├── message.js
  9. ├── require.js
  10. ├── topic.js
  11. ├── underscore.js
  12. └── user.js

15.4 用require.js加载

上面定义了项目需要的所有模块,知道了app.js相当于程序的入口,那么要怎么在页面开始呢?

就像一开始介绍的require.js的用法一样,只需要在index.html中加入一个js引用,和一段定义即可:

  1. // index.html
  2. <script data-main="/static/js/app.js" src="/static/js/require.js"></script>
  3. <script>
  4. require.config({
  5. baseUrl: '/static',
  6. shim: {
  7. underscore: {
  8. exports: '_'
  9. },
  10. },
  11. paths: {
  12. "jquery": "js/jquery",
  13. "underscore": "js/underscore",
  14. "backbone": "js/backbone",
  15. "user": "js/user",
  16. "message": "js/message",
  17. "topic": "js/topic",
  18. "appview": "js/appview",
  19. "approuter": "js/approuter",
  20. "app": "js/app",
  21. }
  22. });
  23. </script>

需要解释的是上面的那个 shim 的定义。因为underscore并不没有对AMD这样的模块规范进行处理,因此需要进行模块化处理,有两种方式:1.修改underscore的源码,加上 define(function(require, exports, module) 这样的定义;2. 采用requirejs提供的shim来进行处理。

15.5 捋捋结构

上面把文件拆分了一下,但是没有把template从页面提取出来。有兴趣的可以自己尝试下。最后我们来整理一下项目的结构。

../images/wechat-arch.png

具体的代码也可以到 wechat 中去看,在requirejs这个分支,代码中添加了socketio,但是对上面的介绍没有影响。


还没有评论.