【问题标题】:Cannot read property 'View' of undefined无法读取未定义的属性“视图”
【发布时间】:2012-12-19 02:24:11
【问题描述】:

这是我第一次将 require.js 与主干一起使用,我正在努力寻找我的观点的问题:

Cannot read property 'View' of undefined // search.js:8

我的目录结构是:

.
├── index.php
└── js
    ├── app.js
    ├── lib
    │   ├── backbone.js
    │   ├── backbone-min.js
    │   ├── jquery-min.js
    │   ├── require.js
    │   └── underscore-min.js
    ├── main.js
    ├── model
    ├── router.js
    ├── text.js
    └── view
        ├── error.js
        └── search.js

我的main.js

require.config({
  paths: {
    jquery: 'lib/jquery-min',
    underscore: 'lib/underscore-min',
    backbone: 'lib/backbone-min',
    templates: '../templates'
  }

});

require([
  'app'
], function(App){
  App.initialize();
});

我的app.js

define([
  'jquery',
  'underscore',
  'backbone',
  'router', // Request router.js
], function($, _, Backbone, Router){

  var initialize = function(){
    // Pass in our Router module and call it's initialize function
    Router.initialize();
  }

  return {
    initialize: initialize
  };
});

我的router.js

define([
  'jquery',
  'underscore',
  'backbone',
  'view/search', // requests view/search.js
], function($, _, Backbone, SearchView){

  var AppRouter = Backbone.Router.extend({
    routes: {
      "": "home"
    }
  });

  var initialize = function(){
    var app_router = new AppRouter;
    app_router.on('route:home', function(){
      var homeView = new SearchView();
      homeView.render();
    });
    Backbone.history.start();
  };
  return {
    initialize: initialize
  };
});

还有我的view/search.js:

define([
  'jquery',
  'underscore',
  'backbone',
  'text!templates/search.html'
], function($, _, Backbone, searchTemplate){

  // console.log($,_,Backbone);

  var SearchView = Backbone.View.extend({
    ...
  });

  return SearchView;
});

当我取消注释上面的 console.log 时,_Backbone 都是 undefined$ 不是。我错过了什么?我所有的 lib 文件都是最新版本。

【问题讨论】:

    标签: javascript backbone.js requirejs


    【解决方案1】:

    Backbone 和 Underscore 不符合 AMD 标准。默认情况下,它们不提供与 RequireJS 兼容的接口。

    在上个版本中,RequireJS provide a useful way to solve the problem:

    你的 main.js:

    require.config({
      shim: {
        underscore: {
          exports: '_'
        },
        backbone: {
          deps: ['underscore', 'jquery'],
          exports: 'Backbone'
        }
      },
      paths: {
        jquery: 'lib/jquery-min',
        underscore: 'lib/underscore-min',
        backbone: 'lib/backbone-min',
        templates: '../templates'
      }
    
    });
    
    require([
      'app'
    ], function(App){
      App.initialize();
    });
    

    【讨论】:

    • 感谢您拯救我的一天,先生!顺便说一句,下划线也需要导出。
    【解决方案2】:

    要扩展 BAK 的答案,您还需要提供一个 baseUrl:

    require.config({
      baseUrl: 'js',
    ...
    });
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      • 2022-01-14
      • 1970-01-01
      • 2020-04-06
      相关资源
      最近更新 更多