使用从Visual Studio 2010中的mindscape Web工作台(coffeescript源)生成的javascript

时间:2011-10-11 17:49:04

标签: javascript coffeescript

这个咖啡脚本代码

    class TestCoffee
        constructor: (@saludo) ->

    helloCoffee: ->
        alert @saludo+" Coffee v7"

使用mindscape web workbench 2.0.332.18684

生成以下javascript
    (function() {
        var TestCoffee;
        TestCoffee = (function() {
          function TestCoffee(saludo) {
            this.saludo = saludo;
          }
          TestCoffee.prototype.helloCoffee = function() {
            return alert(this.saludo + " Coffee v7");
          };
          return TestCoffee;
        })();
    }).call(this);

我应该如何在asp.net mvc 3视图中使用此代码?

我正在用

导入js代码
<script src="@Url.Content("~/Scripts/helloCoffe.js")" type="text/javascript"></script>

并尝试使用

    <script type="text/javascript">

    $(document).ready(function () {

        var coffee;

        coffee = TestCoffee("Jelouuuu");

        coffee.helloCoffee();

    });

</script>

我收到了TestCoffee未定义的错误

那么,我该如何使用呢?

提前致谢!

2 个答案:

答案 0 :(得分:2)

这是设计:

  

虽然为了清晰起见,但在本文档中已被删除   CoffeeScript输出包含在匿名函数中:(function(){   ......})();这种安全包装与自动发电相结合   var关键字,使污染非常困难   全局命名空间。

     

如果您想为其他脚本创建顶级变量,   将它们作为属性附加到窗口或导出对象中   CommonJS的。存在主义运算符(如下所述)给你一个   找出添加位置的可靠方法;如果你是两个目标   CommonJS和浏览器:出口?此

http://jashkenas.github.com/coffee-script/

我通常使用jQuery $ .extend将函数推送到jquery命名空间以供其他脚本使用。

IE:

file1.coffee

$ ->
    $.extend
        ErrorAlert: (text) ->
            simpleGritter $("#SuccessGritter"), text
            return false

file2.coffee

$ ->
    $("#right").ajaxError (event, request, settings) ->
        $.ErrorAlert("Some kind of bad thing happened at: " + settings.url)

答案 1 :(得分:2)

简单的更改将允许此功能。在类声明中添加一个“@”符号:

class @TestCoffee
    constructor: (@saludo) ->

    helloCoffee: ->
        alert @saludo+" Coffee v7"

并改变实例化课程的方式。在课堂上使用“新”

coffee = new TestCoffee("Jelouuuu");

那应该能得到你想要的东西。