【问题标题】:require.js dependencies - how to incorporate dependency methods in additional scriptrequire.js 依赖项 - 如何将依赖项方法合并到附加脚本中
【发布时间】:2015-01-14 18:48:51
【问题描述】:

我在一个主干.js 项目中使用 raphael.js。导入 raphael 就像一个魅力(这个版本是 AMD 兼容的)。一切都按预期工作。这里的“app”是在另一个 app.js 文件中定义的预定义全局对象。

define(['jquery', 'underscore', 'app', 'backbone','raphael' ], function($, _, app, Backbone, Raphael) {

var AppView = Backbone.View.extend({

initialize: function() { 

    app.paper = Raphael(0, 0, app.w, app.h);

} ... }) })

现在我的 app.paper 拥有所有 Raphael 方法。太棒了!

我刚刚在 Raphael API 中发现,我可以使用 Raphael.el 和 Raphael.fn 添加自己的预定义方法

initialize: function() { 

    app.paper = Raphael(0, 0, app.w, app.h);

    Raphael.el.myfill = function(){
        this.attr('fill', '90-#fff-#000');
    }

    app.paper.circle(x,y,r).myfill(); //it works! (Brilliant!)

    }

}

我的问题是,我怎样才能将 Raphael.el.myfill 定义与其他 Raphael.fn.mydefinedmethods 一起放入另一个 javascript 文件并将其带入上面的 AppView?

我不想让冗长的定义阻塞我的 AppView 文件,我还想提供关于我在不同视图中使用哪些 Raphael.[el|fn] 定义的可变性。但是由于这些对象构造函数已经是我已经作为依赖项引入的 Raphael.js 对象的一部分,所以我不确定如何使用 require.js 协议将 Raphael.el 和 Raphael.fn 定义分开。在 require.js 之前,我只需将这些定义放在另一个 myRaphaelDefs.js 文件中,在我的 html 中添加另一个“脚本”标签,它们都将始终可用,但这是 2015 年,我已经跳上了模块化 js跟风。

我使用的是与 AMD 兼容的 RedRaphael 分支,因此我在 Raphael.js 本身上没有“定义”包装器。如果这个库确实带有这样的包装器,我可能会尝试将外包定义作为依赖项直接添加到 Raphael.js 中。 (不是一个选项)RedRaphael 可以直接与 require.js 一起使用,因此那里没有“定义”包装器。

【问题讨论】:

    标签: backbone.js requirejs dependencies


    【解决方案1】:

    我们所做的是在我们的库周围添加一个包装器,并使用 require.config 中的 map 选项对其进行路由,因此包装器获取原始库,但其他所有内容都会抛出包装器:

    raphael-wrapper.js:

    define(['raphael'], function (Raphael) {
        Raphael.el.myfill = function(){
            this.attr('fill', '90-#fff-#000');
        };
        return Raphael;
    });
    

    require.config:

    {
        paths: {
            'raphael': '/path/to/rahpael'
        },
        map: {
            '*': {
                'raphael': '/path/to/rahpael-wrapper'
            },
            '/path/to/rahpael-wrapper': {
                'raphael': 'raphael'
            }
    
        }
    }
    

    【讨论】:

    • 感谢您的回答,乌兹。我以前没有使用过地图选项。好的,我试试看。
    • 太棒了,它有效!很高兴我问,因为我在 require.js API 中没有看到任何解释这种情况的内容
    猜你喜欢
    • 1970-01-01
    • 2013-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-08
    • 1970-01-01
    • 2014-12-29
    • 1970-01-01
    相关资源
    最近更新 更多