将模型传递给本地存储查看的问题

时间:2012-11-20 07:44:29

标签: backbone.js local-storage

在我的应用程序的初始化功能期间,我想默认使用我的搜索页面并将我的LeagueCollection作为模型传递。

我遇到了一个问题,我可以在这里添加一个手表。我的应用程序中的searchResults初始化并看到模型:Array [3]如预期的那样,  但是当调用视图中的this.model.toJSON()时,我得到的错误对象没有方法toJSON。

此代码在内存集合中运行良好,然后我切换到使用backbone.localstorage.js在本地存储应用程序数据。

所以我的问题是:为什么模型没有在视图中填充?

在我的main.js中我有

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

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

    },
    ...
});

在我的搜索页面视图中

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;
    },
    ...
});

1 个答案:

答案 0 :(得分: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();
    } 
});
相关问题