Memento pattern
by Andy Bulka
HTML
Memento
<div id="out"></div>
CoffeeScript
class PrintToDiv
constructor: (currdiv=$('#out')) ->
this.setdiv(currdiv)
setdiv: (currdiv) ->
@currdiv = currdiv
pr: (msg='', crlf=true, hr=false) ->
crlf=true if msg==''
@currdiv.append msg
@currdiv.append ' ' if not crlf and not hr
@currdiv.append '<br>' if crlf
@currdiv.append '<hr>' if hr
p = new PrintToDiv()
##
class PreserveableText
class Memento
constructor: (@text) ->
constructor: (@text) ->
save: (newText) ->
memento = new Memento @text
@text = newText
memento
restore: (memento) ->
@text = memento.text
pt = new PreserveableText "The original string"
p.pr pt.text # => "The original string"
memento = pt.save "A new string"
p.pr pt.text # => "A new string"
pt.save "Yet another string"
p.pr pt.text # => "Yet another string"
pt.restore memento
p.pr pt.text # => "The original string"