Question

I have created a very basic backbone app, to understand how it works.

In the router, I just wanna display just 1 model, i.e. a user, not the whole collection, by passing an id in the url, how to do that?

For example, I'd like to do someapp.com/app/#user/2, and this would display just user no2 details.

Please see my work in jsfiddle

// router
var ViewsRouter = Backbone.Router.extend({

  routes: {
    '': 'viewOne',
    'one': 'viewOne',
    'two': 'viewTwo',
    'user/:id': 'user'
  },

  viewOne: function() {
    var view = new TheViewOne({ model: new TheModel });
  },

  viewTwo: function() {
    var view = new UserView({ model: new TheModel });
  },

  user: function(id) {
    // how to get just 1 user with the corresponding id passed as argument
    // and display it???
  }
});

Many thanks.

Was it helpful?

Solution

https://github.com/coding-idiot/BackboneCRUD

I've written a complete Backbone CRUD with no backend stuff for beginners. Below is the part where we get the user from the collection and show/render it.

View

  var UserEditView = Backbone.View.extend({
         render: function(options) {
             if (options && options.id) {
                 var template = _.template($("#user-edit-template").html(), {
                     user: userCollection.get(options.id)
                 });
                 this.$el.html(template);
             } else {
                 var template = _.template($("#user-edit-template").html(), {
                     user: null
                 });
                 // console.log(template);
                 this.$el.html(template);
             }
             return this;
         },

Router

router.on('route:editUser', function(id) {
     console.log("Show edit user view : " + id);
     var userEditView = new UserEditView({
         el: '.content'
     });
     userEditView.render({
         id: id
     });
 });

Update

Particularly, sticking to your code, the router will look something like this :

user: function(id) {
     var view = new UserView({ model: userCollection.get(id) });
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top