简体   繁体   中英

Backbone events not firing after rendered view

I have a view being rendered in the router, but after it's rendered none of the events will fire. The following is my view:

function(Global, util, user, userMenu) { 
        /*userMenu is the template*/
        var UserMenuView = Backbone.View.extend({
            initialize: function() {
                this.template = _.template(userMenu);
            },
            render: function() {
                var container = $(this.el);
                container.empty().append(this.template());
                return container;
            },
            events: {
                "tap #about-user-menu" : "launchAbout",
                "keydown #about-user-menu": function(e) { if (e.which === 13) this.launchAbout(e); },
                "tap #help-user-menu" : "launchHelp",
                "keydown #help-user-menu": function(e) { if (e.which === 13) this.launchHelp(e); },
                "tap #resources-user-menu" : "launchResources",
                "keydown #resources-user-menu": function(e) { if (e.which === 13) this.launchResources(e); },
            },
            launchAbout: function(e){
                e.preventDefault();
                alert("about");
            },
            launchHelp: function(e){
                e.preventDefault();
                alert("help");
            },
            launchResources: function(e){
                e.preventDefault();
                alert("resources");
            }
        });
        return UserMenuView;
    }

This is how I am rendering the view in the router:

showUserMenu: function(){
    var userMenu = new UserMenuView();
    userMenu.render();
}

this.template() in your code returns just a HTML string, causing the problem.

so you should try to append el element of view which has HTML string and also Event bindings

now in your view assign HTML to el

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

in your router

$('#menu').append(UserMenuView.render().el);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM