简体   繁体   中英

How to fetch the backbone collection and pass to view?

i am facing problem in backbone collection.

this is my router

    var LanguageRouter = Backbone.Router.extend({
    routes: {
        '': 'defaultaction',
        'section/:key': 'sectionview',
    }
});

collection is

 var LanguageCollection = Backbone.Collection.extend({
    model: LanguageModel,
    url: '/lang'
});

and app.js

 var initialize = function () {
    var language_router = new LanguageRouter(),
        parent_view = new ParentView(),
        list_collection = new LanguageCollection(),
        list_collection.fetch();
    language_router.on('route:defaultaction', function () {
        list_view = new LanguageListView({
            collection: list_collection,
            template: _.template(templates.languagelistsingle)
        });

    });

Here , after fetching the list_collection i tried passed the collection to language_view but i am getting empty collection only. How to fix this... Thanks in advance

Fetch is not synchronous, so you cannot call it in one line and use the return on the next line. The correct way using backbone is use listenTo or On (depending on the backbone version)

You could change this part:

list_collection = new LanguageCollection();
this.listenTo(list_collection, "sync", this.someFunction()); 
\\here we are listening the sync event that is automatically fired by backbone when a model or collection is synced with the server.

list_collection.fetch();


someFunction:function(){
    //Logic with the collection content...
}

To learn more about events, please take a read here: http://backbonejs.org/#Events-catalog

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