Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone's preferred way of triggering navigate on link clicks?

Tags:

backbone.js

Is there a preferred way to trigger Router.navigate in Backbone when a user clicks a link?

For instance a template might have a link <a href="/logout">Log Out</a>. Is the preferred approach really to use a custom class and attach a click handler to that class in the view? This seems to generate tons of duplicate code so I'm looking for a better way.

like image 524
Tristan Avatar asked Dec 28 '25 22:12

Tristan


1 Answers

The way to handle this kind of thing is to extend the Backbone objects ( in this case the View). You'll notice in the Backbone docs that this is encouraged, and necessary given its minimalist code base. I'd recommend checking out Marionette (on Github) and the site Backbone patterns for good ways to extend the Backbone core.

For example, maybe you extend View with a method that wires up the navigation handlers as you like:

Backbone.View.prototype.wireupNavs = function() {
    var that = this;
    this.$el.find("a[role=nav]").each(function() {
        var target = $(this).attr('href');
        that.bind("click", router.navigate(target);
    });
}

Then any a tag you want as a Backbone nav element, you'd just decorate with the role="nav" attribute; and call this.wireupNavs() in the initializer function of the appropriate views.

like image 198
McGarnagle Avatar answered Dec 30 '25 23:12

McGarnagle