【问题标题】:Problems with passing model to view from local storage从本地存储传递模型到视图的问题
【发布时间】:2012-11-08 06:01:37
【问题描述】:

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

我遇到了一个问题,我可以在我的应用程序初始化中向 this.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;
    },
    ...
});

【问题讨论】:

  • 你想要一个集合还是SearchPage里面的模型,如果你想要一个集合你应该叫它collection而不是model
  • 抱歉术语不正确 - 我的意思是模型
  • 但是如果是合集,就应该叫collection,否则只会迷惑大家。视图构造函数特别对待 collection 属性,就像对待 model 参数一样:backbonejs.org/#View-constructor
  • 是的,查看了您的链接 - 所以集合是 this.options 和模型的一部分,我明白为什么这会令人困惑。谢谢!我会稍微改变一下问题。
  • 如果它是一个集合,那么在构造函数调用中调用使用{collection: c},并在视图中将其称为this.collection,这样就不会那么混乱了。

标签: backbone.js local-storage


【解决方案1】:

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();
    } 
});

【讨论】:

  • 效果很好,谢谢!我去看看文档。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 2015-06-04
  • 1970-01-01
相关资源
最近更新 更多