Search code examples
backbone.js

Backbone JS Button Click Event Not Working


I am new to backbone js and I'm struggling to display an alert when clicking on the button displayed in the html page. I am certain I'm doing something foolish, but when i click the button the event doesn't seem to be fired. I have tried to use both submit and click in the events section, but I can't seem to get it to work. I would be very grateful if someone could help me out, thanks!

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Event Test</title>
  <script src="../../external/jquery.js"></script>
  <script src="../../external/underscore.js"></script>
  <script src="../../external/backbone.js"></script>  
</head> 
<body>
<div id="standard-input-form"></div>
<script>

  var MovePalletView = Backbone.View.extend({
    initialize: function() {
  },

  events: {
    'submit' : 'move'
  },

  render: function(event) {
    this.$el.append('<button type="button" value="Submit"></button>');
    $("#standard-input-form").html(this.$el.html());
    return this;
  },

  move: function() { 
    alert("You clicked it");
    }
  });

  $(function(){ 
    var movePalletView = new MovePalletView()
    movePalletView.render();      
   })

  </script>    
</body>
</html>

Solution

  • Render function appends just HTML string which doesn't have any events bound. Instead append HTML element (just remove .html() part):

    events: {
        'click' : 'move'
    },
    
    render: function(event) {
        this.$el.append('<button type="button" value="Submit"></button>');
        $("#standard-input-form").html(this.$el);
        return this;
    },
    

    However, this is not really a good solution, because you would have to use click event instead of proper submit. Much better approach is to initialize your MovePalletView with #standard-input-form as this.$el:

    var MovePalletView = Backbone.View.extend({
        el: '#standard-input-form',
        initialize: function () {},
    
        events: {
            'submit': 'move'
        },
    
        render: function (event) {
            this.$el.append('<button type="submit" value="Submit"></button>');
            return this;
        },
    
        move: function (e) {
            e.preventDefault();
            alert("You clicked it");
        }
    });
    

    A few notes. First of all, make sure you have button type="submit" it will trigger onsubmit event. Then you need to create View object on the form element as the root (el: '#standard-input-form'). Then you will be able to bind to its onsubmit event.