aboutsummaryrefslogtreecommitdiff
path: root/samples/CoffeeScript/browser.coffee
diff options
context:
space:
mode:
authorJoshua Peek <josh@joshpeek.com>2012-07-23 15:52:49 -0500
committerJoshua Peek <josh@joshpeek.com>2012-07-23 15:52:49 -0500
commit7b6caa0f6c7603aabb5e6ed657e24aaddbeafc78 (patch)
treeec0522eae75bb04ae73d28ae3f599682a2bfdaeb /samples/CoffeeScript/browser.coffee
parent314f0e485227915931db361be14d308a210bedea (diff)
Rename samples subdirectories
Diffstat (limited to 'samples/CoffeeScript/browser.coffee')
-rw-r--r--samples/CoffeeScript/browser.coffee55
1 files changed, 55 insertions, 0 deletions
diff --git a/samples/CoffeeScript/browser.coffee b/samples/CoffeeScript/browser.coffee
new file mode 100644
index 0000000..5ed0bea
--- /dev/null
+++ b/samples/CoffeeScript/browser.coffee
@@ -0,0 +1,55 @@
+# Override exported methods for non-Node.js engines.
+
+CoffeeScript = require './coffee-script'
+CoffeeScript.require = require
+
+# Use standard JavaScript `eval` to eval code.
+CoffeeScript.eval = (code, options = {}) ->
+ options.bare ?= on
+ eval CoffeeScript.compile code, options
+
+# Running code does not provide access to this scope.
+CoffeeScript.run = (code, options = {}) ->
+ options.bare = on
+ Function(CoffeeScript.compile code, options)()
+
+# If we're not in a browser environment, we're finished with the public API.
+return unless window?
+
+# Load a remote script from the current domain via XHR.
+CoffeeScript.load = (url, callback) ->
+ xhr = new (window.ActiveXObject or XMLHttpRequest)('Microsoft.XMLHTTP')
+ xhr.open 'GET', url, true
+ xhr.overrideMimeType 'text/plain' if 'overrideMimeType' of xhr
+ xhr.onreadystatechange = ->
+ if xhr.readyState is 4
+ if xhr.status in [0, 200]
+ CoffeeScript.run xhr.responseText
+ else
+ throw new Error "Could not load #{url}"
+ callback() if callback
+ xhr.send null
+
+# Activate CoffeeScript in the browser by having it compile and evaluate
+# all script tags with a content-type of `text/coffeescript`.
+# This happens on page load.
+runScripts = ->
+ scripts = document.getElementsByTagName 'script'
+ coffees = (s for s in scripts when s.type is 'text/coffeescript')
+ index = 0
+ length = coffees.length
+ do execute = ->
+ script = coffees[index++]
+ if script?.type is 'text/coffeescript'
+ if script.src
+ CoffeeScript.load script.src, execute
+ else
+ CoffeeScript.run script.innerHTML
+ execute()
+ null
+
+# Listen for window load, both in browsers and in IE.
+if window.addEventListener
+ addEventListener 'DOMContentLoaded', runScripts, no
+else
+ attachEvent 'onload', runScripts