Reputation: 404
I am using CoffeeScript classes in conjunction with a jQuery and am loading another HTML page via ajax that, in turn, references another javascript but am having trouble getting the ajax loaded page to see the classes loaded in scripts by the parent page:
The parent page loads a javascript file (compiled from CoffeeScript):
<script src="/assets/global.js?body=1" type="text/javascript"></script>
In the CoffeeScript file there is a class:
class App
constructor: ->
...
I am loading another web page using:
$.ajax({
url: '/import/show',
success: (data) =>
$('#content').html(data)
})
This page, in turn references another Coffee/JavaScript file:
<script src="/assets/import.show.js?body=1" type="text/javascript"></script>
When this loaded javascript file contains:
alert('test')
The alert is raised, as expected. This demonstrates that the loading code is working correctly. However, if the child script contains:
app = new App()
I get an error:
Uncaught ReferenceError: App is not defined
This also happens if I put the code within a document ready function:
$(=> a = new App())
Does anyone have any idea how I can make the classes in scripts loaded by the parent page available in script loaded by child pages which are loaded via ajax?
Upvotes: 2
Views: 1739
Reputation: 605
Simply put @ before your class name.
class @App
This will generate the following:
(function() {
this.App = (function() {
...
Since you define the class when window is the this, it will be globally accessible.
Upvotes: 6
Reputation: 404
I think I have discovered why this is happening and found a work around. When I looked at the compiled script (rather than the CoffeeScript) I discovered the following:
(function() {
var App
App = (function() {
...
Then it dawned on my that 'class App' defines the class as a var within a function meaning that it is only accessible from within that CoffeeScript file.
The workaround is for me to define my classes as:
class window.App
constructor: ->
...
This then sets the scope of the class to the window DOM object which is then accessible from within the ajax loaded script.
Does anyone know if there is a better way to do this, or does this seem like the right approach?
Upvotes: 0