anders
anders

Reputation: 835

Backbone View click hello world

I'm trying to do a very simple hello world with Backbone. After reading docs and examples I think this should work, but doesn't do anything when I click:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
    <script type="text/javascript">
      var AppView = Backbone.View.extend({

          events: {
              'click #new': 'createNew'
          },

          //CREATE
          createNew: function(){
              alert('yea');
          }

      });

      var app_view = new AppView();
    </script>
  </head>
  <body>

    <a href="#new" id="new">new</a>
  </body>
</html>

Am I missing something? What could be wrong?

Upvotes: 2

Views: 2225

Answers (1)

Benoit Garret
Benoit Garret

Reputation: 13675

You have two problems here:

  1. A Backbone view is tied to a specific DOM element. You have to attach your view to the DOM before it can respond to events.
  2. The DOM may not be ready when your script executes, you have to wrap the view creation code with $(document).ready.
<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
    <script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>
    <script type="text/javascript">
      var AppView = Backbone.View.extend({

          events: {
              // the element IS the link, you don't have to specify its id there
              'click': 'createNew'
          },

          //CREATE
          createNew: function(){
              alert('yea');
          }

      });

      $(document).ready(function() {
        // attach the view to the existing a element
        var app_view = new AppView({
          el: '#new'
        });
      });
    </script>
  </head>
  <body>

    <a href="#new" id="new">new</a>
  </body>
</html>

Upvotes: 6

Related Questions