Using non-AMD compatible javascript module with require.js?

后端 未结 3 896
鱼传尺愫
鱼传尺愫 2020-12-24 14:58

I\'m using require.js to help organize my Backbone.js based application.

I\'m trying to figure out the right way to use a 3rd party javascript library that is not AM

3条回答
  •  一生所求
    2020-12-24 15:37

    UPDATE: I have forked an AMD compatible backbone-tastypie called backbone-tastypie-amd.

    While sander's solution would work, its a little annoying to do the whole nested require thing every time you want backbone.

    backbone-tastypie is what is called a "traditional script". You can solve the issue in 4 ways.

    1. Make backbone-tastypie AMD compatible yourself. You can do this in one of two ways. Option 1 would be to never include backbone directly - only backbone-tastypie. Then modify backbone tastypie to ensure backbone is required.

      var root = this;
      var Backbone = root.Backbone;
      if (!Backbone && (typeof require !== 'undefined')) Backbone = require('backbone').Backbone;
      

      However this isn't very nice because essentially it will start downloading backbone after backbone-tastypie has loaded (synchronous). It also doesn't give requirejs the full understanding of how these modules relate, and thats the point right? So lets wrap backbone-tastypie in a define():

      (function (factory) {
              if (typeof define === 'function' && define.amd) {
                      // AMD. Register as an anonymous module.
                      define(['backbone'], factory);
              } else {
                      // RequireJS isn't being used. Assume backbone is loaded in 
      
                                       
                    
提交回复
热议问题