Search code examples
backbone.jsbackbone-viewsbackbone-events

How to use events on backboneJS views


So I'm trying to learn how to use the backbone events using the documentation but I'm stuck at the events part, when I click on the page class content it should alert "page tag has been clicked" but it throws an error on the commented line.

<body>
        <div class="page"></div> 
</body>

<script type="text/javascript">
    var View = Backbone.View.extend({
        initialize: function()
        {
            this.render(); 
        },
        render: function()
        {
            this.$el.html('Click me im an element');
        },
        events: function()
        {
                       //Uncaught SyntaxError: Unexpected token : 
            "click .page" : "callme"
        },
        callme: function()
        {
            alert('page tag has been clicked');
        }
    });

    var view = new View({
        el: '.page'
    });
</script>

Solution

    1. Your events property must be either a hash

      events: {
          "click .page" : "callme"
      }
      

      or a function that returns a hash

      events: function() {
          return {
              "click .page" : "callme"
          };
      }
      
    2. You indicate a .page selector but that's your view element. Either use a global selector

      events: {
          "click " : "callme"
      }
      

      or set your el to an ancestor node, for example

      var view = new View({
          el: 'body'
      });