Skip to content

Instantly share code, notes, and snippets.

@kaheglar
Last active December 23, 2015 13:09
Show Gist options
  • Save kaheglar/6639811 to your computer and use it in GitHub Desktop.
Save kaheglar/6639811 to your computer and use it in GitHub Desktop.
Backbone Nested Views with MutationObservers.
<!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>
Backbone.$('body').append('<x-my-tag/>')
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)
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