Skip to content

Instantly share code, notes, and snippets.

@Bluebie
Created February 17, 2009 22:48
Show Gist options
  • Save Bluebie/66043 to your computer and use it in GitHub Desktop.
Save Bluebie/66043 to your computer and use it in GitHub Desktop.
A simple smilies parser class for MooTools, broken
var SmiliesParser = new Class({
initialize: function(smiledata) {
this.data = smiledata;
this.sensor = new RegExp($H(smiledata).getValues().map(function(item) {
return item.map(function(i) {
return '(' + i.escapeRegExp() + ')';
}).join('|');
}).join('|'), 'g');
},
applyToTextNode: function(startNode) {
var smiles = []; var self = this;
var result; var node = startNode;
while (result = this.sensor.exec(node.data)) {
console.log(node.data);
var newNode = node.splitText(result.index);
node = newNode.splitText(result[0].length);
smiles.push(newNode);
}
if (smiles.length > 0) console.log(JSON.encode(smiles.map(function(i) {return i.data;})));
smiles.each(function(smile) {
var src;
Hash.getKeys(self.data).each(function(smileImg) {
self.data[smileImg].each(function(test) {
if (smile.data == test) src = smileImg;
});
});
var img = new Element('img', {alt: smile.data, title: smile.data, src: src});
smile.parentNode.replaceChild(img, smile);
});
},
applyToElement: function(element) {
var self = this;
$A($(element).childNodes).each(function(node) {
switch (node.nodeType) {
case Node.TEXT_NODE:
self.applyToTextNode(node);
break;
case Node.ELEMENT_NODE:
self.apply(node);
break;
}
});
}
});
//...
window.addEvent('domready', function() {
window.smilies = new SmiliesParser(smiliesData);
});
//... later ...
smilies.applyToElement(someElement);
// logs 'window' as the 'this' object and raises an error about applyToTextNode not being in the window object and not being a function.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment