如何跨多个文件跨越javascript命名空间? [英] How to span javascript namespace across multiple files?

查看:183
本文介绍了如何跨多个文件跨越javascript命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我永远忽略了javascript。几年前我开始使用jQuery,所以我可以顺利通过。但是当我开始更多地使用TDD时,我决定昨天真正深入了解javascript(之后可能还有coffeescript)。

I have ignored javascript forever. I started using jQuery a few years back so I could get by. But as I've started doing TDD more I decided yesterday to really dive into javascript (and possibly coffeescript after that).

在我的ASP.NET Web Forms应用程序中,我有许多页面,目前大多数页面没有大量的JavaScript。我正在改变这一点。我正在使用Jasmine和Chutzpah来创建我的测试。

In my ASP.NET Web Forms application I have many pages and currently most of those pages do not have a ton of javascript. I'm in the process of changing that. I'm using Jasmine with Chutzpah to create my tests.

我正在按照我的测试通过并按预期失败。但后来我想创建一个命名空间,所以我不会在全球范围内踩踏。

I was moving along with my tests passing and failing as expected. But then I wanted to create a namespace so I wouldn't be trampling all over global space.

阅读本文后:
http://enterprisejquery.com/2010/ 10 /如何 - 好习惯 - 可以鼓励 - 坏javascript习惯 - 第1部分/

我决定尝试使用自执行匿名函数的模式:本文的第2部分(公共和私人)部分。它似乎具有最大的灵活性,似乎很好地封装了东西。

I decided to try and use the pattern from the Self-Executing Anonymous Function: Part 2 (Public & Private) section of the article. It appears to have the most flexibility and appears to encapsulate things very well.

我有一个名为/ Scripts的文件夹。在该文件夹下是我正在使用的一些框架,如jQuery,jasmine,(twitter)bootstrap和modernizr。我还有一个名为/ Site的子文件夹,我根据页面将我的代码放在多个文件中。 (product.js,billing.js等)

I have a folder called /Scripts. Under that folder are some of the frameworks I'm using like jQuery, jasmine, (twitter) bootstrap and modernizr. I also have a subfolder called /Site where I am putting my code for the site in multiple files based on the page. (product.js, billing.js, etc.)

在/ Scripts / Site下我向/ Tests(或Specs)添加了一个子文件夹,其中包含文件(product_test。 js,billing_tests.js等。)

Under /Scripts/Site I added a subfolder to /Tests (or Specs) that have the files (product_test.js, billing_tests.js, etc.).

没有名称空间,一切都很好。我有一个用 padLeft 辅助函数创建的utility.js文件。然后我在另一个.js文件中使用了全局padLeft。我的测试都奏效了,我很高兴。然后我决定找出命名空间并将我的Scripts / Site / utility.js更改为:

Without having namespaces everything is fine. I have a utility.js file I created with a padLeft helper function. I then used that global padLeft in another .js file. My tests all worked and I was happy. I then decided to figure out the namespace and changed my Scripts/Site/utility.js to look like:

(function (myns, $, undefined) {
    //private property
    var isSomething = true;

    //public property
    myns.something = "something";

    //public method
    myns.padLeft = function (str, len, pad) {
        str = Array(len + 1 - str.length).join(pad) + str;

        return str;
    };


    //check to see if myns exists in global space
    //if not, assign it a new Object Literal
}(window.myns= window.myns|| {}, jQuery ));

然后在我的Scripts / Site / Tests / utility_test.js中我有

Then in my Scripts/Site/Tests/utility_test.js I have

/// <reference path="../utility.js" />

describe("Namespace myns with public property something", function () {
    it("Should Equal 'something'", function () {
        expect(myns.something).toEqual('something');
    });
});

通过这个极其简单的测试,我期待myns.something能够以'某事的字符串值返回。

With this extremely simple test I was expecting myns.something to come back with the string value of 'something'.

事实并非如此。它返回 undefined

It doesn't. It comes back undefined.

那么,如何在多个文件中使用javascript命名空间?

很抱歉很长时间的介绍,但我认为这可能有助于解释为什么我这样做。我也提出了所有这些,因为我很乐意听到关于这种设置是完全错误或部分错误的想法等等。

Sorry for the long introduction, but I figured it may help explain the why of me doing it this way. I also put all of this because I'm open to hearing ideas about how this setup is totally wrong or partially wrong or whatever.

感谢您花时间阅读本文问题。

Thanks for taking the time to read this question.

更新:已解决
谢谢大家的帮助。最有帮助的是来自评论者@ T.J。克劳德。我不知道jsbin工具是否存在,并且在确信上面提到的代码被放入工具中并且结果是正确的之后我知道在我的环境中必须关闭一些东西。

UPDATE: SOLVED Thank you all for your help. The most help came from the commenter @T.J. Crowder. I didn't know the jsbin tool existed and after being convinced that the code I put above was put into the tool and the results were right I knew something had to be off in my environment.

接受的答案中的链接也帮了我很多。在看到语法和逻辑是一致的并且正常工作后,我只需要确定关于我的设置的内容。我很尴尬地说这是我传递jQuery但在我的测试工具中,我试图让它工作,我实际上并没有使用jQuery。这意味着该模块实际上并没有被加载 - 所以myns从未被设置过。

The link in the accepted answer also helped me out a lot. After seeing that the syntax and logic was consistent and working I just had to determine what was off about my setup. I'm embarrassed to say it was me passing in jQuery but in my test harness where I was trying to get this to work I wasn't actually using jQuery. This meant the module wasn't actually being loaded - so myns was never set.

谢谢大家。希望这对未来的某些人有所帮助。如果使用上面的内容,请确保包含jQuery对象。另一个选择是不传入jQuery并从param列表中删除$。

Thanks everyone. Hopefully this may be helpful to someone in the future. If you use the above make sure you include the jQuery object. The other option is to not pass in jQuery and remove the $ from the param list.

推荐答案

尝试将你的名字空间声明放在函数调用之外:

Try putting your name space declaration outside of the function call:

myns = window.myns || {};
(function(myns, $, undefined) {
    ...
}(myns, jQuery));

您现有的语法似乎完全有效,但打破这一行可能有助于弄清楚出了什么问题使用您的可变范围。

Your existing syntax appears to be completely valid, but breaking that line out may help figure out what's going wrong with your variable scope.

这篇关于如何跨多个文件跨越javascript命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆