Created
October 12, 2013 18:34
-
-
Save peteblois/6953310 to your computer and use it in GitHub Desktop.
Allows binding events to functions on your model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just include it on the page then use syntax such as: