Skip to content

Instantly share code, notes, and snippets.

Created April 9, 2014 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/10329377 to your computer and use it in GitHub Desktop.
Save anonymous/10329377 to your computer and use it in GitHub Desktop.
htmlparser = require('htmlparser2')
domlite = require("dom-lite")
document = domlite.document
HTMLElement = domlite.HTMLElement
# Element.prototype.innerXML = Element.prototype.innerHTML
# Element.prototype.outerXML = Element.prototype.outerHTML
Function::getter = (prop, get) ->
Object.defineProperty @prototype, prop, {get, configurable: yes}
Function::setter = (prop, set) ->
Object.defineProperty @prototype, prop, {set, configurable: yes}
addChildren = (root, nodes) ->
for node in nodes
if node.type == 'text'
el = document.createTextNode node.data
else if node.type == 'comment'
el = document.createComment node.data
else if node.type == 'tag'
el = document.createElement node.name
for name, value of node.attribs
el.setAttribute name, value
addChildren(el, node.children)
else
continue
root.appendChild el
class Element extends HTMLElement
@getter 'innerXML', -> @innerHTML
@getter 'outerXML', -> @outerHTML
@setter 'innerXML', (xml) -> @_setInnerXML(xml)
@setter 'outerXML', (xml) -> @_setOuterXML(xml)
_setInnerXML: (xml) ->
parsed = (err, nodes) =>
throw err if err
@childNodes = []
addChildren(this, nodes)
parser = new htmlparser.Parser(new htmlparser.DomHandler(parsed))
parser.write(xml)
parser.end()
_setOuterXML: (xml) ->
parsed = (err, nodes) =>
throw err if err
throw 'Too few/many nodes' if nodes.length != 1
node = nodes[0]
throw 'Dont do that' if node.name.toUpperCase() != @nodeName
@childNodes = []
@attributes = []
for name, value of node.attribs
@setAttribute name, value
addChildren(this, nodes[0].children)
parser = new htmlparser.Parser(new htmlparser.DomHandler(parsed))
parser.write(xml)
parser.end()
# constructor: (nodeName) ->
# super(nodeName)
# outerXML: ->
# @outerHTML()
# innerXML: ->
# @innerXML()
class Box extends Element
constructor: ->
super 'BOX'
class Model extends Element
constructor: ->
super 'MODEL'
class Script extends Element
constructor: ->
super 'SCRIPT'
describe 'box', ->
beforeEach ->
@b = new Box
it 'should have outerXML', ->
expect(@b.outerXML).toMatch /<BOX/
expect(@b.innerXML).toEqual ""
it 'should set via outerXML', ->
@b.outerXML = "<box position='1 2 3' />"
expect(@b.getAttribute('position')).toEqual '1 2 3'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment