JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://underscorejs.org/underscore.js"></script>
<script src="http://backbonejs.org/backbone.js"></script>
<div class="container1"></div>
JavaScript
// Testing the statement from jQuery `.on()` docs:
//
// "Event handlers are bound only to the currently selected elements;
// they must exist on the page at the time your code makes the call to
// .on()" -- http://api.jquery.com/on/
// The "SUT"
var View = Backbone.View.extend({
template: _.template('<div class="inner"><button>Say hello</button></div>'),
initialize: function (options) {
this.name = options.name;
this.$el.append($(this.template()));
},
events: {
'click button': function () {
console.log('Hello from ' + this.name);
}
},
render: function () {
this.$el.empty().append($(this.template()));
}
});
// Here's an element that's in the DOM when the script runs:
var $container1 = $('.container1');
// An instance of the SUT, its el is in the DOM when delegated events are bound:
var view = new View({
el: $container1,
name: 'View 1'
});
// Now let's make an element that's not in the DOM:
var $container2 = $('<div class="container2"></div>');
// Delegated events will be bound on an element that's not in the DOM:
var view2 = new View({
el: $container2,
name: 'View 2'
});
$('body').append(view2.el);