[Snowman] Alias for window.story.state in every function

Snowman creates an object whose contents get saved in savegames. This object is window.story.state.

When you use Snowman templates <% … %>, window.story.state is abbreviated as just s

However, when you write javascript outside <% … %>, for example to define functions in the Javascript passage, s is not available, and you have to write window.story.state: 17 characters longer.

My code is complex enough that this has become a serious obstacle to code readability. Many lines are terribly long and repetitive. What would you do to avoid writing window.story.state?

I can think of two options:

  1. Not using Javascript passages. Using regular passages, printing them with story.render(), and including the code in these passages inside <% … %>
  2. Start every function with a line like: s = window.story.state, which I think would assign s as a local variable to the same object as window.story.state and change its values directly.

Do you think any of these options has serious downsides or conflict possibilities? I can’t think of any, but I’ll always be a Javascript newbie and I feel very wary about it.

Thanks!

Well, the first thing you can do is shorten window.story.state to just story.state thus saving yourself typing seven characters…
(TWEE Notation based example)

:: Story Javascript [script]
/* Assign a value to a story variable. */
story.state.name = "Jane";

:: Start
Character Name: <%= s.name %>.

And, as you’ve already noted, you can assign a reference to the story.state object to a local variable within your JavaScript function…

:: Story Javascript [script]
/* Assign a value to a story variable. */
story.state.name = "Jane";

/* Create personal NameSpace and custom functions. */
window.GE = {
	logname: function () {
		var s = story.state;
		console.log("name: " + s.name);
	}
};

:: Start
Character Name: <%= s.name %>.

Log Name to Console
<% GE.logname() %>
1 Like

Thanks! So, in this code:

window.GE = {
	logname: function () {
		var s = story.state;
		console.log("name: " + s.name);
	}
}

… the line var s = story.state is safe? Nothing strange should happen?

The result of that line is that the local variable s references the same Generic Object as the story.state property reference does.

So it’s basically no different than doing something like the following in your own JavaScript code…

var first = {name: "Jane Doe", age: 18};
var second = first;

…which results in both the first and second variables referencing the same Generic Object…