最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add a module function to the window object with require.js? - Stack Overflow

programmeradmin0浏览0评论

In my current project I am working with krpano, a multi resolution panorama image viewer for the browser. You can add clickable hotspots on a panorama and define a function, that is executed, when the hotspot is clicked.

The method I want to be executed is inside a require.js module, but the krpano library only calls methods, that are attached to the global window object.

How can I add my method from a module to the window object, so that I still have access to all of my other dependent modules?

My application consists of plenty modules with dependencies.

Thanks.

In my current project I am working with krpano, a multi resolution panorama image viewer for the browser. You can add clickable hotspots on a panorama and define a function, that is executed, when the hotspot is clicked.

The method I want to be executed is inside a require.js module, but the krpano library only calls methods, that are attached to the global window object.

How can I add my method from a module to the window object, so that I still have access to all of my other dependent modules?

My application consists of plenty modules with dependencies.

Thanks.

Share Improve this question asked Aug 21, 2014 at 8:52 tellobtellob 1,2503 gold badges16 silver badges33 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You're not giving much details but two ways to do it e to mind. What is most appropriate really depends on the specifics of your application.

  1. This is what I'd prefer to do if I had to leak a function from a module because it does not make the module itself leak the function. If this module is reusable at all, then I could use it in another project where I don't have to leak anything. I'd write my module like any other AMD module and then, I'd have glue code pull out what I need to leak. The module (in a mod.js file):

    define(["a", "b"], function (a, b) {
        return { 
            foo: function () {},
            bar: function () {}
        };
    });
    

    The glue code:

    require(["mod"], function (mod) {
        window.foo = mod.foo; // Leak the function I need for **this** project.
    });
    
  2. Make the module itself leak a function. This makes the module inherently leaky and harms reuse but sometimes some modules are so tied to the specific project they are created for that reuse is not going to happen, so...

    define(["a", "b"], function (a, b) {
        function foo () {}
        window.foo = foo;
        return { 
            foo: foo,
            bar: function () {}
        }
    });
    
发布评论

评论列表(0)

  1. 暂无评论