Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js click event not firing

Going through a very basic tutorial on backbone.js views.

The expected behavior is to call the render function when #sayhello button is clicked. Render simply uses jQuery's html method to put "hello Bud Abbot" in el.

But when I click the #sayhello button, nothing happens. No errors or anything. I set a breakpoint in firebug and watch it just skip the render function.

Here's the js:

App = (function($){
jQueryView = Backbone.View.extend({
    initialize: function(){
        this.el = $(this.el);
    }
});

HelloWorldView = jQueryView.extend({
    el: $('#helloworld'),
    events:{ 'click #sayhello': 'render'
    },
    initialize: function(params){
        jQueryView.prototype.initialize.call(this);
        this.name = params.name;
    },

    render: function(){
        console.log("rendering");
        this.el.html("hello " + this.name);
    }
});

var self = {};
self.start = function(){
    new HelloWorldView({name: 'Bud Abbot'});
};
return self;

});

And here's the html:

    <div id="helloworld"></div>
<button id="sayhello">Say Hello</button>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.4/underscore-min.js"></script>
<script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></script>

What seems strange is when I change this:

new HelloWorldView({name: 'Bud Abbot'});

to this:

new HelloWorldView({name: 'Bud Abbot'}).render();

the render method is called, but when I try to do it with an event - no dice. Any help to understand what I'm doing wrong is greatly appreciated.

like image 499
rakitin Avatar asked Oct 06 '11 04:10

rakitin


2 Answers

It's because #sayhello is not part of your view. Try putting #sayhello inside #helloworld:

<div id="helloworld">
    <button id="sayhello">Say Hello</button>
</div>
like image 74
Johnny Oshika Avatar answered Oct 19 '22 20:10

Johnny Oshika


If you are dynamically rendering the page using the templates, then in the render function consider calling view.setElement(...);

this.setElement($('#login-container'));

like image 36
Saba Avatar answered Oct 19 '22 19:10

Saba