【问题标题】:marionette serializeData no models in collectionmarionette serializeData 集合中没有模型
【发布时间】:2013-07-30 09:18:41
【问题描述】:

我为单页应用程序设置了 Marionette 和 Handlebars。我没有开始这个项目;它最初是由其他人开发的。

我设法找出其他文件中的内容,但我无法弄清楚这一点。

所以,我有models/order.coffee

Model = require './model'
Collection = require './collection'

module.exports = class OrderModel extends Model
  # This is the *real* orders model
  idAttribute: 'uid'
  defaults:
    title: 'some order'

module.exports = class Orders extends Collection
  model: OrderModel

  url: base_url+'history/'

  initialize: =>
    super
    @fetch()

  parse: (response) =>
    return response.objects

parse 之所以存在是因为后端返回数据的方式。 response.objects 包含创建模型的 JSON 对象列表,即OrderModelinstances\

接下来是views/SettingsOrderView.coffee

template = require './templates/settings/orders'

module.exports = class SettingsOrdersView extends Backbone.Marionette.ItemView
    template: template
    events: 'click #back_to_options': 'goToOptions'

    serializeData: =>
        data = @.collection
        setTimeout (-> console.log(data.models)), 5000
        $.each data.models, (m_index, m) =>
            console.log(m)

        return {items: @.collection}

我的问题是在模板中我做{{#each items}},但它们是OrderModel 的实例,所以它们在Handlebars 中没用。我需要将它们作为 JSON 对象,但由于某种原因(实际上是 collection.fetch())没有在 serializeData 中填充 @.collection.models。 5 秒后(如 setTimeout 所示)data.models 是我需要的列表,但 each 未执行,因为当时 data.models 是一个空列表。

如前所述,我需要对模型进行 JSON 化,但不可用。我该如何解决这个问题?

如果您需要其他数据,请发表评论,我会发布。

谢谢。

【问题讨论】:

    标签: coffeescript handlebars.js marionette


    【解决方案1】:

    为了呈现集合,Marionette 提供了一个 CollectionView:https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.collectionview.md

    有关何时将 CollectionView 或 ItemView 用于多个项目的讨论,请参阅这篇出色的文章: http://lostechies.com/derickbailey/2011/10/11/backbone-js-getting-the-model-for-a-clicked-element/

    要序列化模型,您可以在模型上调用 model.toJSON()。或者,您可以简单地使用 get() 函数或通过在模型和/或集合上编写自己的 JSON 方法来获取单个属性。在这种情况下,您可以简单地在集合上调用该方法。

    但我猜你真正的问题是对 fetch() 的调用。如果我对您的理解正确,那么当您尝试使用它们时,模型似乎已经丢失。 Backbone 为这种情况提供了一个成功回调。当数据准备好时,将调用此回调。

    http://backbonejs.org/#Collection-fetch

    现在,我自己从来没有使用过这个——使用 websockets 和 promises 而不是主干同步机制——但是看看这篇文章,这可能对你的情况有用:

    http://lostechies.com/derickbailey/2012/02/03/get-a-model-from-a-backbone-collection-without-knowing-if-the-collection-is-loaded/

    【讨论】:

    • 谢谢。最后,我删除了集合并在模型本身上使用了success 回调。这有点像我在这里做的事情,但符合我的目的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    相关资源
    最近更新 更多