简体   繁体   中英

PreventDefault event not working in Backbone view

I'm learning Backbone.js from lightweight django and i'm unable to get the below function from triggering a default event.

the below is my html for the button

<script type="text/html" id="header-template">
    <span class="title">Scrum Board Example</span>
    <% if (authenticated ) { %>
        <nav>
            <a href="/" class="button">Your Sprints</a>
            <a href="#" class="logout">Logout</a>
        </nav>
    <% } %>
</script>

and this is my backbone view

var HeaderView = TemplateView.extend({
    tagName: 'header',
    templateName: '#header-template',
    events: {
        'click a.logout': 'logout'
    },
    getContext: function () {
        return {authenticated: app.session.authenticated()};
    },
    logout: function (event) {
        event.preventDefault();
        console.log('clicked');
        app.session.delete();
        window.location = '/';
    }
});

whenever I click on the a href button - it doesn't seem to be triggering the logout function in my view model.

Am i going wrong somewhere else?

Thanks,. KJ

If you use preventDefault() there is no reason to use href.

<a class="button">Your Sprints</a>

But if you use window.location = '/' why using preventDefault.

Also using a callback for your delete function could be cool.

var callback = window.location = '/';
app.session.delete(callback);

In app.session.delete:

app.session.delete = function(callback) {
    // do stuff
   if(callback) {
       callback();
   }
}

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