javascript - 使用 RequireJS 加载外部 javascript 库

标签 javascript backbone.js requirejs

我构建了一个我需要在 BackboneJS 项目中使用的小型 javascript 库。 我的问题是,我在使用图书馆时遇到问题。我想我做错了什么,当我试图访问它时,我得到了一个“未定义”。

下面的一些代码,我简化了它。

图书馆看起来像那样 - myLibrary.js:

(function() {
    var myLibrary = this;

    var initialize = function() {
        console.log('initialize');
    };

    myLibrary.otherFunction = function() {
        console.log('otherFunction');
    };
    return myLibrary;
})();

我将我的库放在我的 requirejs 配置中:

requirejs.config({
    paths: {
        jquery: "js/jquery"
        myLibrary: "js/myLibrary"
    }, 
    shim: {
        myLibrary: {
            deps: ['jquery']
        }
    }
});

我正在尝试在 BackboneJS View 中使用我的库

define([
  'jquery',
  'backbone',
  'myLibrary'
], function($, Backbone, myLibrary){
    'use strict';

    return Backbone.View.extend({

        initialize: function() {
            console.log(myLibrary); 
            //myLibrary is undefined here!
            //I'd like to access myLibrary as an object 
            //to access my functions inside..
        }
    });
});

库已加载。我可以在开发者栏的“网络”选项卡中看到它。

如果你知道这里出了什么问题?

谢谢。

最佳答案

按照您现在的方式,您的 myLibrary 脚本实际上正在运行,但是返回值 (return myLibrary;) 正在被丢弃,因为它没有被分配给任何东西。您可以执行以下两项操作之一:

您可以将返回值分配给全局对象上的某些内容并更新您的 shim 配置:

window.myLibrary = (function() {
    var myLibrary = this;

    var initialize = function() {
        console.log('initialize');
    };

    myLibrary.otherFunction = function() {
        console.log('otherFunction');
    };
    return myLibrary;
})();

requirejs.config({
    paths: {
        jquery: "js/jquery"
        myLibrary: "js/myLibrary"
    }, 
    shim: {
        myLibrary: {
            deps: ['jquery'],
            exports: "myLibrary"
        }
    }
});

或者,更好的是,在您的库中实际使用 define:

define(["jquery"], function ($) {
    var myLibrary = this;

    var initialize = function() {
        console.log('initialize');
    };

    myLibrary.otherFunction = function() {
        console.log('otherFunction');
    };
    return myLibrary;
});

关于javascript - 使用 RequireJS 加载外部 javascript 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18004294/

相关文章:

javascript - 在路由组件之外 react 路由器重定向

javascript - 在 Fabricjs 中缩放对象时缺少图案质量

javascript - 我只将最后一个元素添加到 JS 数组中

javascript - jQuery - 获取子级 CSS 反向旋转的父级 Angular 差异

javascript - 模块的 Node 模块多个调用方向

javascript - Backbone : Fetch models in increments

javascript - 在backbonejs中编译模板是什么意思以及更多

jquery-ui - Jquery Draggable 和 Backbone.js 从 droppable 成功回调内部获取对 Backbone 模型的引用

php - Require.js 和 Zend 框架

javascript - 间歇性 RequireJS 加载错误