1

我知道requireJS支持糖语法,以下代码是否正确加载位于js/window/startup.js的模块,具有jquery、下划线和Backbone的依赖关系?

require.config({
  baseUrl: 'http://localhost/js/',
  path: {
    jquery: '/lib/jquery-1.9.1.min',
    underscore: '/lib/underscore-1.4.4',
    backbone: '/lib/backbone-1.0'
  }
});

require([
  './window/startup',
  'jquery',
  'underscore',
  'backbone',
], function(Startup){
  Startup.init();
});

js/window/startup.js 中的代码:

define(function (require) {
  var $ = require('jquery');
      _ = require('underscore');
      Backbone = require('backbone');

  //Test to see if module is being fired
  console.log('The module code has been executed!');

  var init = function(){
    /* SOME CODE */
    //Test to see if the init function has fired
    console.log('The initialize function has fired!');
  }

  return {
    init: init
  }

});

这一切似乎都符合文档,但是当我运行这段代码时,两个控制台消息都没有显示。

4

1 回答 1

2

您的代码中散布着大量语法错误。查看这个 plunker的工作示例。

这是你得到不正确的:

require.config({                         // NEED PARENTHESIS HERE
  baseUrl: 'http://localhost/js/',
  paths: {                               // SHOULD BE paths, NOT path
    jquery: '/lib/jquery-1.9.1.min',
    underscore: '/lib/underscore-1.4.4',
    backbone: '/lib/backbone-1.0'
  }
});                                      // NEED END PARENTHESIS HERE

require([
  './window/startup',
  'jquery',
  'underscore',
  'backbone'                             // GET RID OF TRAILING COMMA
], function(Startup){
  Startup.init();
});

在你的另一个文件中:

define(function (require) {              // GET RID OF EXTRA PARENTHESIS IN HERE
  var $ = require('jquery'),             // SHOULD BE COMMA, NOT SEMICOLON
      _ = require('underscore'),         // SHOULD BE COMMA, NOT SEMICOLON
      Backbone = require('backbone');

  //Test to see if module is being fired
  console.log('The module code has been executed!');

  var init = function(){                 // NEED AN ASSIGNMENT, INSTEAD OF JUST var fn() {}
    /* SOME CODE */
    //Test to see if the init function has fired
    console.log('The initialize function has fired!');
  };

  return {
    init: init
  };

});                                      // NEED END PARENTHESIS HERE

我强烈建议使用报告语法错误的代码编辑器。这将帮助您避免此类问题。

于 2013-08-05T21:41:40.330 回答