Skip to content

Instantly share code, notes, and snippets.

@jkappers
Created August 30, 2012 18:44
Show Gist options
  • Save jkappers/3537204 to your computer and use it in GitHub Desktop.
Save jkappers/3537204 to your computer and use it in GitHub Desktop.
Attach instances of javascript classes to DOM nodes
(function(exports){
// When the DOM is ready...
$(function(){
// ...Find any elements that have a data-view attribute
$('[data-view]').each(function(){
// Store a reference to the node and the data-view attribute value.
var $node = $(this), attr = $node.data('view');
// Create an instance of a class with a name that matches the value of attr,
// pass the node as a parameter to the constructor, and then store the instance
// in the node's data hash.
$node.data(attr, new exports[attr]($node));
});
});
})(window); // Instead of window, use an object that contains your view definitions.
<script>
function AnimalView($element){
this.$element = $element;
}
</script>
<div data-view="AnimalView"></div>
@benlwilliams
Copy link

Word!

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