Skip to content

Instantly share code, notes, and snippets.

@videlais
Last active May 17, 2018 00:42
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save videlais/3250e278d08f43b4b9cf26c15ce8a81e to your computer and use it in GitHub Desktop.
:: StoryTitle
Google Spreadsheet Testing
:: UserScript[script]
/*
A short example of how to load the Sheetrock.js library
using the existing jQuery library as part of Twine 2
and add a on-the-fly variable in SugarCube using
State.variables.
Sheetrock.js (https://github.com/chriszarate/sheetrock)
*/
// Call this function during the "ready" event
$(function() {
// Set the URL to load
// (In this case, the Sheetrock.js library for
// accessing public Google Spreadsheets.)
var URL = "https://cdnjs.cloudflare.com/ajax/libs/jquery-sheetrock/1.1.4/dist/sheetrock.min.js";
// Use getScript() to fetch and run remote JS
$.getScript( URL )
// If everything went well, run done()
.done(function( script, textStatus ) {
// Call loadsheet()
loadSheet();
})
// If it failed, run fail()
.fail(function( jqxhr, settings, exception ) {
console.log("Remote loading failed!");
});
function loadSheet() {
// Define spreadsheet URL.
// (This example holds baseball data.)
var mySpreadsheet = 'https://docs.google.com/spreadsheets/d/1qT1LyvoAcb0HTsi2rHBltBVpUBumAUzT__rhMvrz5Rk/edit#gid=0';
// Run sheetrock using an empty selector
$().sheetrock({
// Set the URL of the Google Spreadsheet
url: mySpreadsheet,
// Set a callback from the results
callback: function (error, options, response) {
// Response holds the data.
// For rows, .rows
// For HTML, .html
// (https://github.com/chriszarate/sheetrock#callback)
// In SugarCube, we can access variables through
// State.variables
State.variables.response = response.rows[0];
},
// Query is based on the SQL-like Google Query Language
// (https://developers.google.com/chart/interactive/docs/querylanguage)
// In this example, select (get) the columns A, B, and C
query: "select A,B,C"
});
}
});
:: Start
We will now wait for the response to load. We do this because there is now a race condition between the loading and parsing the Google Spreadsheet and Twine itself. (A "race condition" is where two or more processes are running at once and one depends on data from the other. They are "racing" each other to finish.)
Since Twine will usually load first, we setup a timer to check for the variable we want and then show the results when they are detected. This delays the "race" until both are where they need to be in order to continue.
<<repeat 1s>>
<<if $response != undefined>>
Response found!
The first three column names (A, B, C) are:
<<print $response.labels[0]>>
<<print $response.labels[1]>>
<<print $response.labels[2]>>
<<stop>>
<</if>>
<</repeat>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment