Skip to content

Instantly share code, notes, and snippets.

@naganowl
Last active August 29, 2015 13:56
Show Gist options
  • Save naganowl/9200389 to your computer and use it in GitHub Desktop.
Save naganowl/9200389 to your computer and use it in GitHub Desktop.
tl;dr: Don't re-render views that are delegating events as the delegation will be lost (without further action).

Writing down the pains I've rediscovered multiple times with Chaplin item views in a CollectionView (Though they can be applied to regular Chaplin views as well).

Numerous times, I have run into instances where I am calling this.delegate('click',...) on initialize of an item view to obtain the behavior of routing from a generic tabular list to a detailed item view and finding that the click delegation is not working for some reason.

These painful times after ardurous debugging have led to the same conclusion that I am documenting now to avoid repeating again in the future. Essentially, the root cause was somewhere else within the view, I had an event handler to do a render which effectively blows away the delegation since the old nodes are tossed away.

Below is a simple project that I lightly modified (Credit goes to @egeste for coming up with it originally) that exhibits that item views have no problem delegating clicks in a simple CollectionView.

Also, thanks to @danevans for helping to come up with the solution.

{
"name": "ChapTest",
"dependencies": {
"backbone": "latest",
"chaplin": "latest",
"jquery": "latest",
"requirejs": "latest",
"underscore": "latest"
}
}
<html lang="en">
<head>
<script src="bower_components/requirejs/require.js" data-main="main"></script>
</head>
<body></body>
</html>
require.config({
paths: {
jquery: 'bower_components/jquery/dist/jquery',
underscore: 'bower_components/underscore/underscore',
backbone: 'bower_components/backbone/backbone',
chaplin: 'bower_components/chaplin/chaplin'
},
shim: {
jquery: {exports: 'jQuery'},
underscore: {exports: '_'},
backbone:{
deps: ['underscore', 'jquery'],
exports: 'Backbone'
}
}
});
require(['chaplin', 'underscore'], function(Chaplin, _) {
var collection = new Chaplin.Collection([{id: 1}, {id: 2}, {id: 3}]);
var ItemView = Chaplin.View.extend({
initialize: function() {
this.delegate('click', function() { alert('THANKS'); });
},
render: function() { this.$el.text('Click me!'); }
});
var CollectionView = Chaplin.CollectionView.extend({
itemView: ItemView,
container: document.body,
getTemplateFunction: function() {}
});
var view = new CollectionView({
collection: collection
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment