require.js Uncaught TypeError: Property '$'

2019-09-09 21:49发布

问题:

I'm trying to use require.js for the first time, however I'm getting the error:

Uncaught TypeError: Property '$' of object # is not a function.

 require.config({
      shim: {

       "jquery": {
            exports: '$'
        },

        underscore: {
          exports: '_'
        },
        backbone: {
          deps: ['underscore', 'jquery'],
          exports: 'Backbone'
        }
      },
      paths: {
        jquery: '//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min',
        underscore: '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min',
        backbone: '//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min',
        templates: '/referralgenie/templates/'
      }

    });

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

It states the error is in backbone.js so I'm finding it hard to debug.

The error comes from the line here:

Backbone.history.start();

In my Router file:

// Filename: router.js
define([
  'jquery',
  'underscore',
  'backbone',
  'views/CampaginView',
  'views/RewardView',
  'views/FriendRewardView',
  'views/ParticipantView'
], function($, _, Backbone, CampaginView, RewardView, FriendRewardView, ParticipantView) {


   var AppRouter = Backbone.Router.extend({
           routes: {
               ':id': 'portal-home' // matches http://example.com/#anything-here
           }
    });


  var initialize = function(){

    var app_router = new AppRouter;

    app_router.on('route:portal-home',function(id) {
      var campaignView = new CampaginView();
      campaignView.render({id: id});
    });




    Backbone.history.start();
  };
  return {
    initialize: initialize
  };
});

回答1:

This is a hunch based on this SO question/answer and based on reading the code of Backbone.js.

I think Backbone is having trouble finding jQuery so you'll have to set it yourself. Try to do it by using a shim with an init function for Backbone:

    backbone: {
      deps: ['underscore', 'jquery'],
      exports: 'Backbone',
      init: function (_, $) { Backbone.$ = $; return Backbone; }
    }