Last active
December 23, 2015 13:09
-
-
Save kaheglar/6639811 to your computer and use it in GitHub Desktop.
Backbone Nested Views with MutationObservers.
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> | |
<title>Self Initializing Backbone View</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<script src="jquery.js"></script> | |
<script src="underscore.js"></script> | |
<script src="backbone.js"></script> | |
<script src="self-initializing-view.js"></script> | |
<script src="my-view.js"></script> | |
<script src="main.js"></script> | |
</head> | |
<body> | |
</body> | |
</html> |
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
Backbone.$('body').append('<x-my-tag/>') |
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
var MyView = Backbone.View.Extend({ | |
tagName: 'x-my-tag', | |
initialize: function () { | |
this.render() | |
}, | |
render: function () { | |
this.$el.html('x-my-tag is rendered') | |
} | |
}) | |
selfInitializingView(MyView) |
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 selfInitializingView (View) { | |
if (!View) { | |
return | |
} | |
var selector = determineSelector(View) | |
new MutationObserver(function (mutations) { | |
mutations.forEach(function (mutation) { | |
if (mutation.type === 'childList') { | |
var $addedNodes = Backbone.$(mutation.addedNodes) | |
, $els = $addedNodes | |
.filter(selector) | |
.add($addedNodes.find(selector)) | |
new View({ el: $els }) | |
} | |
}) | |
}).observe(document.querySelector('body'), { | |
attributes: false, | |
childList: true, | |
characterData: false | |
}) | |
return View | |
} | |
function determineSelector (View) { | |
if (View.prototype.id) { | |
return '#' + View.prototype.id | |
} | |
else { | |
return View.prototype.tagName | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment