MrFoh
MrFoh

Reputation: 2701

backbone.js View event handling

I just started playing around with backbone.js and am enjoying the quirks of using it. However am trying to use it for handling events in views for a site am working on. Am also using namespaces to organise my code

    var App = App || {};
    App.Views = App.Views || {};
    App.Views.Sidebar = Backbone.View.extend({
                el:  '#app-wrapper',

                events : {
                    "click #rf":"test"
    ;           },

                test: function(e) {
                    alert("testing");
                }
            })
        }
  });

Heres the html, its just a skeleton of the site

<html>
<head>
    <title>Shopping List</title>
    <script type="text/javascript" src="jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="underscore.js"></script>
    <script type="text/javascript" src="backbone.js"></script>
    <script type="text/javascript" src="app.js"></script>
    <script type="text/javascript">
    App.Views.Sidebar;
    </script>
</head>

<body>

<div id="app-wrapper">

    <div id="app-header">
        <ul>
            <li id="rf">Test</li>
        </ul>
    </div>

</div>

</body>
</html>

However this snippet doesn't seem to work, the test() method is not called when click the #rf element. Am doing something wrong, am pretty new to this.

Upvotes: 0

Views: 594

Answers (1)

Alladinian
Alladinian

Reputation: 35646

You have not instantiated your view. Try something like this:

var myView = new App.Views.Sidebar();

(instead of: App.Views.Sidebar; )

Also don't forget to instantiate your views once the document has been loaded. Something like this (if you use JQuery):

$(function() {

  // Initialize Backbone views.
  var myView = new App.Views.Sidebar();

});

Upvotes: 4

Related Questions