Skip to content

Instantly share code, notes, and snippets.

@peteblois
Created October 12, 2013 18:34
Show Gist options
  • Save peteblois/6953310 to your computer and use it in GitHub Desktop.
Save peteblois/6953310 to your computer and use it in GitHub Desktop.
Allows binding events to functions on your model
(function(scope) {
var EventBinding = function(element, type, model, path) {
this.element = element;
this.type = type;
this.listener = null;
this.observer = new PathObserver(model, path, this.valueChanged, this);
this.valueChanged(this.observer.value);
};
EventBinding.prototype.valueChanged = function(value) {
if (this.listener) {
this.element.removeEventListener(this.type, this.listener, false);
}
this.listener = value;
if (this.listener) {
this.element.addEventListener(this.type, this.listener, false);
}
};
EventBinding.prototype.close = function() {
if (this.listener) {
this.element.removeEventListener(this.type, this.listener, false);
}
this.observer.close();
this.observer = undefined;
this.listener = undefined;
this.element = undefined;
};
var originalBind = scope.Element.prototype.bind;
scope.Element.prototype.bind = function(name, model, path) {
if (name.indexOf('on-') == 0) {
this.unbind(name);
return this.bindings[name] =
new EventBinding(this, name.substr(3), model, path);
}
return originalBind.call(this, name, model, path);
};
})(window);
@peteblois
Copy link
Author

Just include it on the page then use syntax such as:

<div on-click='{{handleClick}}'></div>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment