Search code examples
javascriptbackbone.jsbackbone-viewsbackbone-routing

How Get ID value from router in view using backbone.js


I have a router.js and a view.js

I want the value of ID passed from router.js page in my view page. How can i get that??

Here is my router:

/**
 * Created by HP on 6/26/2014.
 */

var app = app || {};
app.Router = Backbone.Router.extend({
    routes: {
        '': 'index',
        'color/:id': 'color'
    },
    index: function(){
        console.log("index called");
    },
    color: function(id){
        console.log("color called"+id);
        //viewPage.render(id);
    }
});

new app.Router;
Backbone.history.start();

In my view i want the value of id which i need to set in a html element Here is my View /** * Created by HP on 6/17/2014. */

// site/js/views/library.js
var app = app || {};
app.LibraryView = Backbone.View.extend({
 el: '#ulMenu',
 initialize: function(options) {
this.collection = new app.Library();
this.collection.fetch({reset: true});
this.render();
this.listenTo( this.collection, 'reset', this.render );
 },
    events:{
        'click':'show'

    },
    show: function(){

        this.subRender();
    },
 render: function() {
      },

    subRender: function() {
        $("#content").html("Color Name: ");
    }
 });

Solution

  • i think you can try passing all your arguments as options

    Router

    var app = app || {};
    app.Router = Backbone.Router.extend({
        routes: {
            '': 'index',
            'color/:id': 'color'
        },
        index: function(){
            console.log("index called");
        },
        color: function(id){
            console.log("color called"+id);
            var libraryView = new LibraryView({
                  id : id    //passing it as option to views initalize.
             });
        }
    });
    
    new app.Router;
    Backbone.history.start();
    

    View

    var app = app || {};
    app.LibraryView = Backbone.View.extend({
     el: '#ulMenu',
     initialize: function(options) {
    this.receivedId = this.options.id; // id is catched here
    this.collection = new app.Library();
    this.collection.fetch({reset: true});
    this.render();
    this.listenTo( this.collection, 'reset', this.render );
     },
        events:{
            'click':'show'
    
        },
        show: function(){
    
            this.subRender();
        },
     render: function() {
          },
    
        subRender: function() {
            $("#content").html("Color Name: ");
        }
     });