Skip to content

Instantly share code, notes, and snippets.

@jiewmeng
Created August 31, 2012 13:45
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jiewmeng/3552832 to your computer and use it in GitHub Desktop.
Save jiewmeng/3552832 to your computer and use it in GitHub Desktop.
MathJax/Markdown Editor in CoffeeScript

MathJax/Markdown (GitHub Markdown via marked) Editor in CoffeeScript

Usage

The CoffeeScript/JavaScript will be very simple, just init the editor

define [
	"jquery",
	"MathJaxMarkdownEditor"
], ($, Editor) ->
	editor = new Editor()

	jQuery ->
		editor.init()

The HTML will look like

<textarea name="editor" id="editor"></textarea>
<div id="editor-preview"></div>
<div id="editor-buffer"></div>

How it works

The Editor will listen to keyup events of #editor. When that happens there will be a small delay before the actual update or re-render. Updates will be done in buffer which is the swapped with preview. Buffer will be hidden while preview shown

References/Credits

define [
"marked",
"jquery",
"mathjax"
], (marked, $, MathJax) ->
# see: http://cdn.mathjax.org/mathjax/latest/test/sample-dynamic-2.html
class MathJaxMarkdownEditor
inputName: "#editor"
previewName: "#editor-preview"
bufferName: "#editor-buffer"
delay: 200 # delay after each key stroke before updating
$preview: undefined # jQuery object to preview element
$buffer: undefined # jQuery object to buffer element
timeout: undefined # store setTimeout
isRunning: false # true when MathJax running
oldText: "" # to check if update is required
# should be called after document loaded
init: ->
@$input = $ @inputName
@$preview = $ @previewName
@$buffer = $ @bufferName
@callback = MathJax.Callback ["createPreview", @]
@callback.autoReset = true # makes sure can run more than once
@$input.on "keyup", @update
# After MathJax has updated the buffer element,
# Swap the preview with the updated buffer
swapBuffer: ->
$buffer = @$preview
$preview = @$buffer
@$buffer = $buffer
@$preview = $preview
@$preview.html marked(@$preview.html())
@$buffer.hide()
@$preview.show()
# Checks to see if theres a pending update (@timeout set).
# Then setup update to trigger after delay (if more keys
# pressed, update callback will be reset to be called later)
update: =>
if @timeout then clearTimeout(@timeout)
@timeout = setTimeout @callback, @delay
createPreview: =>
@timeout = undefined
if @isRunning then return
text = @$input.val()
if text is @oldText then return
@$buffer.html(text)
@oldText = text
@isRunning = true
MathJax.Hub.Queue ["Typeset", MathJax.Hub, @buffer], ["previewDone", @]
previewDone: =>
@isRunning = false
@swapBuffer()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment