RequireJs模块中的UnderscoreJs Mixins

时间:2015-01-07 00:42:14

标签: javascript requirejs underscore.js mixins

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

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:

我对它进行了修改,但它对我来说仍然无效 我这样做了:
main.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']);
});

requireconfig.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,_) {

1 个答案:

答案 0 :(得分:1)

require内的define似乎完全没必要,并且确实会使其他模块使用此模块的方式复杂化,因为一旦加载模块,无法保证mixins 实际上已注册。这是因为require是异步的,define 将在传递给require的代码运行之前返回。

我可以像这样添加一个mixin到Underscore。一旦模块获得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>