0

During the initialize function of my app I would like to default to my search page and pass my LeagueCollection as the model.

I am encountering an issue where I can add a watch to this.searchResults in my App initialize and see models: Array[3] as expected, but when the this.model.toJSON() in the view is called I get the error object has no method toJSON.

This code was working fine with a in memory collection and then I switched to using backbone.localstorage.js to store the app data locally.

So my question is: why is the model not populated in the view?

In my main.js I have

var AppRouter = Backbone.Router.extend({
    routes: {
        "": "list",
    ...
    },
    initialize: function () {

        this.searchResults = new LeagueCollection();
        this.searchPage = new SearchPage({
            model: this.searchResults.fetch()
        });
        this.searchPage.render();

    },
    ...
});

In my Search Page view

window.SearchPage = Backbone.View.extend({

    initialize:function () {
        this.template = _.template(tpl.get('search-page'));
    },

    render:function (eventName) {
        var self = this;

        $(this.el).html(this.template(this.model.toJSON()));
        this.listView = new LeagueListView({el: $('ul', this.el), model: this.model});
        this.listView.render();

        return this;
    },
    ...
});
4

1 に答える 1

3

このメソッドcollection.fetchはコレクションを返しません。これは非同期です。おそらくあなたが望むのは、そのsuccessコールバックを使用することです:

this.searchResults = new LeagueCollection();

var self = this;
this.searchResults.fetch({ 
    success: function(collection, response) {
        self.searchPage = new SearchPage( { model: collection } );
        self.searchPage.render();
    } 
});
于 2012-11-20T08:03:51.353 に答える