Skip to content

Instantly share code, notes, and snippets.

@dannyamey
Created January 11, 2012 17:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dannyamey/1595792 to your computer and use it in GitHub Desktop.
Save dannyamey/1595792 to your computer and use it in GitHub Desktop.
Backbone.js key event example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Untitled</title>
<style>
#example {
background: #f00;
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<a href="javascript:view.remove();">remove view</a>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://documentcloud.github.com/underscore/underscore-min.js"></script>
<script src="http://documentcloud.github.com/backbone/backbone.js"></script>
<script>
// Example view implementation
var ExampleView = Backbone.View.extend({
// bind events outside of the view in initialize
initialize: function() {
// bind all methods to `this` scope
_.bindAll(this);
$(document).on('keydown', this.keydown);
$(document).on('keyup', this.keyup);
},
keydown: function(event) {
console.log('keydown');
},
keyup: function(event) {
console.log('keyup');
},
render: function() {
this.el.innerHTML = 'example view';
return this;
},
// override remove to also unbind events
remove: function() {
$(document).off('keydown', this.keydown);
$(document).off('keyup', this.keyup);
Backbone.View.prototype.remove.call(this);
}
});
// Initialise the view
var view = new ExampleView({ id: 'example' });
document.body.appendChild(view.render().el);
</script>
</body>
</html>
@nqthqn
Copy link

nqthqn commented Feb 27, 2015

Uncaught Error: bindAll must be passed function names ?

@justinstander
Copy link

I removed that line and the listeners still worked

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