简体   繁体   中英

Get a model by ID from a collection in backbone js

I'm trying to figure it out how to get a model by it's id and display the same to view. I have setup my router to get the data by id. I tried a lot but unable to find a solution. Any idea on this would be appreciated.

collection.js file:

app.Collections.qualityCollection = Backbone.Collection.extend({
    model: app.Models.qualityModel,
    url: "http://localhost/socialapp/php/fetch.php"
});

var userCollections = new app.Collections.qualityCollection();

userCollections.fetch();

router.js file:

app.Routers.socialRouter = Backbone.Router.extend({
        routes: {
            "" : "homePage",
            "make_friends/:id" : "userProfile",
        },

        userProfile: function() {
            new app.Views.idView({ model: userCollections.get(id) });
        }

    });

    new app.Routers.socialRouter();

    Backbone.history.start();

view.js file:

app.Views.idView = Backbone.View.extend({
    el: $("#app"),

    template: _.template($('#public-profile').html()),

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

    render: function () {
        console.log(this.model); /// undefined
        this.$el.html(this.template( this.model.toJSON() )); 
        return this;
    }
    });

JSON Data from the URL: [ { "id": "1", "firstname": "Abc", "lastname": "Xyz" }, { "id": "2", "firstname": "Klm", "lastname": "Opq" } ]

Expected Router Link: http://localhost/socialapp/#/make_friends/2

To answer your question, you receive the value of route param in the callback. You can just pass it to the view and access it in it's initialize

app.Routers.socialRouter = Backbone.Router.extend({
    routes: {
        "" : "homePage",
        "make_friends/:id" : "userProfile",
    },

    userProfile: function(id) {
        // no reference?
        new app.Views.idView({ collection: userCollections, modelId: id });
    }

});

If you're view is actually an item view, you don't need to pass the entire collection, you can just do the following after fetching the collection in router.

new app.Views.idView({ model: userCollections.get(id) });

Better yet, your view don't need a collection, you just need a model instance with an end point that returns a model's info

userCollections.get(id) should work.

Considering Id is attribute of the model, you can find the model as below too.

userCollections.find(function(model) { return model.get('id') === Id; });

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