+1 vote
asked by (160 points)
edited by

Hello everybody.

I love Twine and the snowman format (because i'm web dev) and I wanted to know why I couldn't declare a js class in the commun part of js script (it says that the class is not known when I went to use it in a passage).

My class is declared like this :

class Quest{
    constructor(target,condition){
        this.target = target;
        this.condition=condition;
    }
}

When I'm not in the passage where it is declared, I can't use it, but it's okay, I understand. It's because of this that I wanted to declare it in the global JS. But it seems to have the same problem that in another passage.

What do I miss ?

 

1 Answer

0 votes
answered by (109k points)
selected by
 
Best answer

NOTE: JavaScript class isn't fully compatible across all brands of web-browser.

Your issue is basically one of Scope.

Basically the JavaScript executed within any Passage is executed in within it's own Local scope and for this particular situation the Story Javascript area can be considered just another Passage, and (by default) code executed within one Local scope can't access code from any Local scope.

So you will need to raise the scope of your Quest class from Local to Global, and you will need a more experienced JavaScript programmer than I to tell you what's the best practice for doing that in the context of a Twine story format like Snowman.
(Ideally you'd want to use a module and export/import the functionality, but I don't know how to do that for a Twine 2 story format like Snowman without having to use JavaScript to dynamically load an external JS file.)

One method I got to work was combining a global Namespace with an anonymously defined class declaration, but again I don't know if this is considered a good practice or not.

/* Defining the Namespace and Class in Story Javascript area. */
window.GE = window.GE || {};

GE.Quest = class {
    constructor(target,condition){
        this.target = target;
        this.condition=condition;
    }
};


/* Accessing the Quest class within a standard Passage. */
<script>
	var quest = new GE.Quest();
	console.log('quest: ' + quest);
</script>

 

commented by (160 points)
edited by
Thanks, I will try it this afternoon, but I think you have the good idea.

It was too long ago I dev with only jquery and Js.

Thanks a lot !

Edit : re-reading what you said I think global namespace will maybe not be best use, but be efficient.

 

Edit 2 : It works ! It's so cool ! Thank you thank you thank you.
Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.
...