简体   繁体   中英

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: ");
    }
 });

Please try following code.

color: function(id){
console.log("color called"+id);
viewPage = new ViewPage({model: new Model({'id':id})})
viewPage.render(id);
}

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: ");
    }
 });

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