Question

Can someone tell me why the following doesnt work please. I am expecting the alert to fire when I click the link

<body>
    <a class="newnote" href="#">Add new note</a>
</body>

<script>
var note = Backbone.Model.extend({});

var notes = Backbone.Collection.extend({
    model: note,
    url: '<?= $this->createUrl('/filenotes/api'); ?>'
});

var note_view = Backbone.View.extend({
    el: 'table',

});

var Appview = Backbone.View.extend({
    el: $('body'),

    events: {
        "a click" : "showForm"
    },
    initialize: function(){
        //alert('hi');  
    },
    showForm: function(){
        alert('hi');
    }
});

var v = new Appview();
</script>

There is a jsfiddle here http://jsfiddle.net/neilcharlton/yj5Pz/1/

Was it helpful?

Solution

Your $("body") selector is firing before your DOM is loaded, so it's returning empty and never binding to the link.

Backbone object definitions are defined with object literals, which means they get evaluated immediately on definition, not when you instantiate the model.

This:

Backbone.View.extend({foo: "bar"})

Is functionally the same as this:

var config = {foo: "bar"};
Backbone.View.extend(config);

Since you have a $("body") selector as the value for el, it gets evaluated as soon as the View configuration is parsed, meaning the DOM has not yet loaded and nothing will be returned.

There are a number of options for solving this... all of which involve delaying the evaluation of the selector until after the DOM is loaded.

My personal favorite is to pass the selector in to the view at instantiation, after the DOM has loaded:

var AppView = Backbone.View.extend({
  // don't specify el here
});

$(function(){
  // after the DOM has loaded, select it and send it to the view
  new AppView({ el: $("body") });
}

Also - like Skylar said, your event was declared wrong.

Here's a working JSFiddle: http://jsfiddle.net/yj5Pz/5/

OTHER TIPS

For starters, the events object is of this syntax:

events: {
    "click a" : "showForm"
},

Besides Derick's answer, take care about the scope of DOM elements, I was trying to trigger a simple click event on an element but my View.el was referencing an non direct parent , then it for some reason (maybe a recursion bug) wasn't working. When I changed the el to "body" css selector everything went fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top