Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js - simple view

I'm trying to run very simple view in backbone.js Here is the code:

(function($){

    window.templateLoaderView = Backbone.View.extend({

        events: {
            'click #add_contact': 'loadTaskPopup'
        },

        initialize: function () {
            alert('templateLoaderView - initialize');
            _.bindAll(this, 'render');
        },


        render: function() {
            alert('templateLoaderView - render');
        },

        loadTaskPopup: function() {
            alert('templateLoaderView - loadTaskPopup');
        }
    });

})(jQuery);
$(document).ready(function() {
    window.templateLoaderView = new templateLoaderView();
});

<div id="add_contact">CLICK HERE</div>

When page loads, it alerts this alert('templateLoaderView - initialize');, but when I click the div, nothing happens. Could you please tell what I do wrong?

like image 233
kaha Avatar asked Sep 09 '26 15:09

kaha


1 Answers

There are a couple of things that are going wrong.

  • When you create the view, it creates this.el as a DIV but it isn't rooted in anything
  • Your event is trying to hook on the DIV of the view, which has no inner #add_contact
  • You don't get an alert for render because nothing is ever calling render.

The most simple way to get your click handler to work is to tell the view which element to attach to:

window.templateLoaderView = new templateLoaderView({el: $("body") });

Going further...

Though, you may want your DIV to be created inside your view... it would go a little something like this:

(function($){

    window.templateLoaderView = Backbone.View.extend({

        template: _.template('<div id="add_contact">CLICK HERE</div>'),

        events: {
            'click #add_contact': 'loadTaskPopup'
        },

        render: function() {
            $(this.el).html(this.template());
            return this;
        },

        loadTaskPopup: function() {
            alert('templateLoaderView - loadTaskPopup');
        }
    });

})(jQuery);

$(document).ready(function() {
    window.templateLoaderView = new templateLoaderView();
    $("body").append(window.templateLoaderView.render().el);
});
like image 157
Brian Genisio Avatar answered Sep 12 '26 04:09

Brian Genisio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!