I have this class written in CoffeeScript:
Notification.js.coffee
class Notification
display: ->
@dom.show()
constructor: (header, messages) ->
@render(header, messages)
Basically, the logic for render() function code is to inject HTML into the DOM (but hidden) and display() method simply shows the DOM element. Now, I have some other class separate to this one where I’m trying to make use of this above class.
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()
Unfortunately, for some reason – I get
TypeError: 'undefined' is not a function (evaluating 'notification.display()')
on the line above where I do notification.display(). The same code works absolutely as expected If I write it within the Notification class (where everything gets wrapped into an IIFE). The load order for above files is: Notification.js and then SharerController.js
What exactly am I missing here?
You’re missing several things:
Notificationin yourSharerControlleris not the same as theNotificationyou’re defining inNotification.js.coffee. I think you’re picking up Chrome’s nativeNotificationand that doesn’t have adisplaymethod.@domin yourNotificationso yourdisplaycall will fail if you ever manage to call it.rendermethod in yourNotificationso yourNotificationconstructor will fail due to the@rendercall.If you’re only including a sample of your
Notificationcode then (2) and (3) aren’t really problems.CoffeeScript wraps the generated JavaScript in a self-executing function something like this:
so your
Notificationisn’t visible outside yourNotification.js.coffeefile. You can make it globally visible by saying:or
or you could use your own namespace as in this other question.
Once you’ve made your
Notificationavailable to the rest of your application you can instantiate your ownNotification, solve your other problems, and finally you’ll be callingdisplayon something that has adisplaymethod.