2012-11-19 81 views
0

我有此类写入的CoffeeScript:无法访问方法在我的CoffeeScript类从类以外

Notification.js.coffee

class Notification 

    display: -> 
    @dom.show() 

    constructor: (header, messages) -> 
    @render(header, messages) 

基本上,对于render()功能码,所述逻辑将HTML注入DOM(但隐藏)和display()方法只需shows DOM元素。现在,我有一些其他课程与这一课分开,我试图利用这个课程。

SharerController.js.coffee

class SharerController 

    post_story: -> 
    # some user action posting something in the app 
    notification = new Notification('Header', ['This story has been posted.', 'You can post more. Would you like to?']) 
    notification.display() 

不幸的是,由于某种原因 - 我得到

TypeError: 'undefined' is not a function (evaluating 'notification.display()')

上面,我做notification.display()行。相同的代码完全按预期工作如果我在Notification类中编写它(所有东西都被包装到一个IIFE中)。上述文件的加载顺序是:Notification.js然后SharerController.js

我在这里错过了什么?

回答

0

你错过几件事情:

  1. NotificationSharerController是不一样的Notification你在Notification.js.coffee定义。我认为你拿起Chrome的原生Notification,并没有display方法。
  2. 您的Notification中没有@dom,因此如果您设法调用它,您的display调用将会失败。
  3. 您的Notification中没有render方法,因此您的Notification构造函数将由于@render调用而失败。

如果您只包含Notification代码的样本,则(2)和(3)不是真正的问题。

CoffeeScript的包装在一个自执行的函数是这样生成的JavaScript:

(function() { 
    // JavaScript goes here... 
}).call(this); 

所以你Notification是不是你Notification.js.coffee文件的外部可见。你可以把它全局可见说:

class window.Notification 
    #... 

class @Notification 
    #... 

,或者您可以使用自己的名称空间as in this other question

一旦你做出Notification提供给您的应用程序的其他部分可以实例自己Notification,解决您的其他问题,最后你会调用东西,有一个display方法display

+0

1,2和3真的不是问题,因为我只是包含了我的代码的一些部分。但是我想出了命名空间,并且正在开展范围界定。 –