javascriptbackbone.jsbackbone-views

Backbone Events in ES6


I have been working with Backbone in ES5 form for quite some time and I'm looking to try and build a new project in ES6. I've built this very basic view just to test out my build processes etc.

I can get the view to render as expected in the el. However, I cannot seem to get the event to fire at all. I'm sure that I'm missing something simple but I cannot seem to find what it is.

import $ from "jquery";
import _ from 'underscore';
import Backbone from 'backbone';

class basicView extends Backbone.View {
	constructor(options) {
		super();
		this.options = options;
		this.events = {
			'click #bc': 'clickHandler'
		};
		this.render();
	}

	render() {
		$(this.options.el).html('<a id="bc" href="#">button</a>');
		return this;
	}

	clickHandler() {
		alert("button clicked");
		return false;
	}
};

$(() => {
	new basicView({
		el: '#container'
	});
});
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>es6</title>

</head>

<body>
  <div id="container">

  </div>
  <script src="ui/js/production/home.js"></script>
</body>

</html>


Solution

  • As you can see in your constructor, you define events after invoking Backbone.View's code that does things like parsing event hash and binding events.

    constructor(options) {
        super();
        // ^---- don't have an event hash when this code executes.
        this.events = { // this is now useless
            'click #bc': 'clickHandler'
        };
    

    super(options) and passing events hash in options might work. Simple and elegant solution: use Backbone.View.extend() instead of class. You are not gaining anything but disadvantages by using class with backbone. You can still use all other ES6 features in your project.