Skip to content

Instantly share code, notes, and snippets.

@xulapp
Created January 23, 2011 04:58
Show Gist options
  • Select an option

  • Save xulapp/791834 to your computer and use it in GitHub Desktop.

Select an option

Save xulapp/791834 to your computer and use it in GitHub Desktop.
var Div = Class({
constructor: function Div() {
if (!(this instanceof Div))
return Div.createInstance(arguments);
this.element = this.cursor = document.createElement('div');
this.stack = [];
},
attr: function attr(name, value) {
this.cursor.setAttribute(name, value);
return this;
},
removeAttr: function attr(name) {
this.cursor.removeAttribute(name);
return this;
},
addClass: function addClass(name) {
this.cursor.classList.add(name);
return this;
},
bind: function bind(type, listener, cap) {
this.cursor.addEventListener(type, listener, !!cap);
return this;
},
delegate: function delegate(selector, type, listener) {
var root = this.cursor;
return this.bind(type, function(event) {
var {target} = event;
while (target !== root) {
if (target.mozMatchesSelector(selector))
break;
target = target.parentNode;
}
if (target !== root)
return listener.call(target, event);
});
},
text: function text(value) {
this.cursor.textContent = value;
return this;
},
html: function html(value) {
this.cursor.innerHTML = value;
return this;
},
append: function append(node) {
if (!node)
node = Div();
this.cursor = this.cursor.appendChild(node.cursor || node);
return this;
},
next: function next(node) {
if (!node)
node = Div();
this.cursor = this.cursor.parentNode.insertBefore(node.cursor || node, this.cursor.nextSibling);
return this;
},
parent: function parent() {
this.cursor = this.cursor.parentNode;
return this;
},
appendTo: function appendTo(node) {
node.appendChild(this.cursor);
return this;
},
remove: function remove() {
document.adoptNode(this.element);
return this;
},
pushc: function pushc() {
this.stack.push(this.cursor);
return this;
},
popc: function popc() {
this.cursor = this.stack.pop();
return this;
},
root: function root() {
this.cursor = this.element;
return this;
},
exec: function exec(fn) {
fn(this.cursor);
return this;
},
run: function run(fn) {
fn.call(this, this.cursor);
return this;
},
times: function times(from, to, fn) {
if (arguments.length < 3)
[from, to, fn] = [0, from, to];
if (to < from) return this;
var stop = {};
for (var i = from; i < to; i++) {
try {
fn.call(this, this.cursor, i, stop);
} catch (e if e === stop) {
break;
}
}
return this;
},
__noSuchMethod__: function(name, args) this.cursor[name].apply(this.cursor, args),
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment