ltx-xpath
Version:
xpath evaluator for ltx
88 lines (68 loc) • 2.62 kB
JavaScript
(function() {
var EventEmitter, evaluate, parse,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
EventEmitter = require('events').EventEmitter;
parse = require('xpath-parser').parse;
evaluate = require('./evaluate').evaluate;
exports.XPath = (function(_super) {
__extends(XPath, _super);
function XPath() {
this.match = __bind(this.match, this); this._expressions = {};
}
XPath.prototype.addExpression = function(xpath, namespaces) {
var exp;
exp = parse(xpath);
exp.xpath = xpath;
exp.namespace = namespaces;
return this._expressions[xpath] = exp;
};
XPath.prototype.addListener = function(event, ns, listener) {
var _ref;
if (listener == null) {
_ref = [null, ns], ns = _ref[0], listener = _ref[1];
}
if (this._expressions[event] != null) {
return XPath.__super__.addListener.call(this, event, listener);
}
this.addExpression(event, ns);
return XPath.__super__.addListener.call(this, event, listener);
};
XPath.prototype.on = XPath.prototype.addListener;
XPath.prototype.once = function(event, ns, listener) {
var _ref;
if (listener == null) {
_ref = [null, ns], ns = _ref[0], listener = _ref[1];
}
if (this._expressions[event] != null) {
return XPath.__super__.once.call(this, event, listener);
}
this.addExpression(event, ns);
return XPath.__super__.once.call(this, event, listener);
};
XPath.prototype.removeListener = function(event) {
var res;
res = XPath.__super__.removeListener.apply(this, arguments);
if (!this.listeners(event).length) {
delete this._expressions[event];
}
return res;
};
XPath.prototype.match = function(elem) {
var event, expression, match, matched, _ref;
matched = false;
_ref = this._expressions;
for (event in _ref) {
expression = _ref[event];
match = evaluate(expression, [elem], expression.namespace);
if (match.length) {
matched = true;
this.emit(event, elem, match);
}
}
return matched;
};
return XPath;
})(EventEmitter);
}).call(this);