Search code examples
backbone.jsmeteorbackbone-viewsbackbone-routing

Backbone js Routes / Views relationship


I am building an app using Meteor and am having trouble understanding the relationship between Routes and Views. I have Routers working properly, but after having done research on calling new Views am baffled.

Do I use App.navigate ? Do I call something like:

var newView = new MyView();

within the proper router function? This is the code I am using (that works) and my app only has two pages - the index page and item view:

var Aphorism = Backbone.Router.extend({
  routes: {
    "saying/:id": "showSaying"
  },
  showSaying: function (id) {
    alert('Saying id ' + id + '.');
  }
});

Solution

  • You define what routes exist in the Router. You usually only need one of those, unless you have a very complex app.

    Then you hook up links and buttons in the app to execute app.navigate when clicked. You can do this with a view or do it yourself with something like jQuery, it's up to you.

    For instance:

    <div id="myButton">Click me!</div>
    
    var myView = Backbone.View.extend({
      el: "#myButton",
      events: {
        "click": "go"
      },
      go: function() {
        myRouter.navigate("/someUrl", {trigger: true});
      }
    });