在 RequireJs 模块中强调 Js mixins

UnderscoreJs Mixins in RequireJs module

本文关键字:Js mixins RequireJs 模块      更新时间:2023-09-26

为我的应用程序所需的 2 个下划线混合编写了这个 requireJs 模型。我将其添加到require.config并加载了文件,但是当我尝试使用2个函数中的任何一个时,我声明它们是未定义的。我知道我做错了什么,但我不知道是什么。

define(['underscore.mixins'], function (module)
{
    require(['underscore'], function (_) {
        _.mixin({
            'toQueryString': function (parameters) {
                var queryString = _.reduce(
                  parameters,
                  function (components, value, key) {
                      components.push(key + '=' + encodeURIComponent(value));
                      return components;
                  },
                  []
                ).join('&');
                if (queryString.length > 0) {
                    queryString = '?' + queryString;
                }
                return queryString;

更新 1:

修改了它,但它仍然对我不起作用。
我这样做了:
主.js:

require([
    '../common/requireConfig'
], function () {
    'use strict';
    requirejs.s.contexts._.config.paths.chai = 'thirdParty/chai';
    requirejs.s.contexts._.config.paths.mocha = 'thirdParty/mocha';
    requirejs.s.contexts._.config.paths.sinon = 'thirdParty/sinon';
    requirejs.s.contexts._.config.shim.mocha = {
        exports: 'window.mocha'
    };
    requirejs.s.contexts._.config.shim.sinon = {
        exports: 'window.sinon'
    };
    //  Then, load all of the plugins needed by test:
    require(['test/plugins']);
});

需要配置.js

define(function () {
    'use strict';
    require.config({
        baseUrl: 'js/',
        enforceDefine: true,
        paths: { ... }
});

require(["underscore", "thirdParty/underscore.mixins"], function (_) {
    _.toQueryString({});
});

但是当我调用该函数时:
在模型文件中

 requestUrl += _.toQueryString(_.extend({
                    key: YouTubeAPIKey
                }, ajaxDataOptions));'

它仍然未定义

更新 2

通过这样做让它工作:
underscore.mixins.js:

define(['underscore'], function (_) {
    _.mixin({
        'toQueryString': function (parameters) {
            var queryString = _.reduce(
                parameters,
                function (components, value, key) {
                    components.push(key + '=' + encodeURIComponent(value));
                    return components;
                },
                []
            ).join('&');
            if (queryString.length > 0) {
                queryString = '?' + queryString;
            }
            return queryString;
        },
        'fromQueryString': function (queryString) {
            return _.reduce(
                queryString.replace('?', '').split('&'),
                function (parameters, parameter) {
                    if (parameter.length > 0) {
                        _.extend(parameters, _.object([_.map(parameter.split('='), decodeURIComponent)]));
                    }
                    return parameters;
                },
                {}
            );
        }
    });
    return _;
});

在我实际使用这些函数的文件顶部:

define([
    'background/collection/songs',
    'background/key/youTubeAPI',
    'background/model/song',
    'common/enum/songType',
    'common/enum/youTubeServiceType',
    'common/utility',
    'thirdParty/underscore.mixins'
], function (Songs, YouTubeAPIKey, Song, SongType, YouTubeServiceType, Utility,_) {

您在define中的require似乎完全没有必要,并且确实会使其他模块如何使用此模块变得复杂,因为一旦加载了模块,就无法保证mixin实际上已注册。这是因为require是异步的,define将在传递给require的代码运行之前返回。

我可以像这样在下划线中添加一个混合。一旦一个模块获得foo,就可以保证mixin被注册到Underscore。

foo.js

define(["underscore"], function (_) {
_.mixin({
    foo: function () { 
        console.log("foo invoked"); 
    }
});
});

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8"/>
    <script type="text/javascript" src="js/require.js"></script>
  </head>
  <body>
    <script>
      require.config({
        baseUrl: "js"
      });
      require(["underscore", "foo"], function (_) {
        _.foo();
      });
    </script>
  </body>
</html>