backbone.localStorage, require.js, “Uncaught TypeError: undefined is not a function”

后端 未结 1 1626
别那么骄傲
别那么骄傲 2021-01-15 04:36

I\'m following Uzi Kilon\'s BackboneJS / RequireJS / backbone.LocalStorage example at http://kilon.org/blog/2012/08/build-backbone-apps-using-requirejs/.

When I

相关标签:
1条回答
  • 2021-01-15 05:12

    The problem lies with the fact that the latest Backbone localStorage is AMD compatible, where as the version in that example is not, hence the shim config.

    The fix

    Remove the shim config for backbone.localStorage, you won't be needing it:

    'backbone.localStorage': {
      deps: ['backbone'],
      exports: 'Backbone'
    }
    

    Then, in Todo.js change the define call from:

    define(['underscore', 'backbone.localStorage'], function(_, Backbone) {
    

    to:

    define(['underscore', 'backbone', 'backbone.localStorage'], function(_, Backbone) {
    

    Why?

    The shim exports config was being used to say 'When I ask for backbone.localStorage, return me Backbone'.

    This allowed 'backbone.localStorage' to be used simply as Backbone inside the Todo module.

    But now backbone.localStorage supports AMD and explicitly returns a value from the define call. So the value of Backbone in Todo.js is no longer the Backbone library, but is actually a constructor for Backbone.LocalStorage

    As far as I understand, the shim config is ignored for AMD modules, or at least should not be used:

    Only use other "shim" modules as dependencies for shimmed scripts, or AMD libraries that have no dependencies and call define() after they also create a global (like jQuery or lodash). Otherwise, if you use an AMD module as a dependency for a shim config module, after a build, that AMD module may not be evaluated until after the shimmed code in the build executes, and an error will occur. The ultimate fix is to upgrade all the shimmed code to have optional AMD define() calls.

    To fix things up the additional dependency needs to be added in Todo.js so that so that the callback parameters match up.

    Hopefully that makes sense.

    0 讨论(0)
提交回复
热议问题