Created
January 11, 2012 17:39
-
-
Save dannyamey/1595792 to your computer and use it in GitHub Desktop.
Backbone.js key event example
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" /> | |
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I removed that line and the listeners still worked