Cannot read property 'View' of undefined

2019-03-27 08:17发布

问题:

This is my first time to use require.js with backbone, and I'm struggling to find the problem with my view:

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

My directory structure is:

.
├── 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

My 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();
});

My 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
  };
});

My 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
  };
});

and my view/search.js:

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

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

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

  return SearchView;
});

When I uncommented the console.log above, both _ and Backbone is undefined but $ isn't. What have I missed? All my lib files are of the latest version.

回答1:

Backbone and Underscore are not AMD-compliant. By default, they don't provide an interface compatible with RequireJS.

In last versions, RequireJS provide a useful way to solve the problem:

Your 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:

To extend BAK's answer, you'll need to provide a baseUrl too:

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