Backbone - 显示一个模型而不是循环遍历集合 - 用CoffeeScript编写

时间:2012-08-24 10:36:31

标签: backbone.js coffeescript underscore.js

我是Backbone的新手,也是CoffeeScript的新手。我有一个从URL检索数据(属性)的集合。在我的homeView中,我将此数据附加到模板并循环遍历它:

<ul>
     <% _.each(data, function (row) { %>
          <li><%= row.get('name') %></li>
     <% }); %>
</ul>

这很好用。

但是,当我想查看单个行(属性)时,我仍然使用相同的集合并更改我的模型(id)中的属性,以更改集合中所调用的URL&amp;只检索一个数据(一个属性)。

我编写它的方式是,在我的个人属性视图中,它仍然循环遍历集合(即使只有行),并将其附加到主视图

class ShowPropertyView extends Backbone.View
    constructor: ->
        super

    initialize: ->
        @Property = new PropertyCollection #New collection
        @Property.PropertiesModel.set({theID: @options.theID}) #Change URL and get one property with a specific ID

    template: _.template($('#showProperty').html())
    #propertyInfoTemplate: _.template($('#propertyInfoTemplate').html())

    render: ->
        #$(@.el).html(@template) #load main template
        @loadResults() #load individual property

    loadResults: ->
        @Property.fetch({
            success: (data) =>
                         $('#propertyInfo').append(@propertyInfoTemplate({data: data.models, _:_})) #Load data into another template & append template to main template
            error: ->
                alert('Unable to load information')
        })

当前模板(接收数据并附加到主模板)看起来像这样(类似于我的homeView模板):

<div>
     <% _.each(data, function (row) { %>
          <div>
               <h3><%= row.get('name') %></h3>
          </div>
     <% }); %>
</div>

我想要实现的是能够将信息传递到单个视图中,并且不再需要在下划线中使用循环语句,而不必将其附加到主视图中(因为它只是一个个别数据)。

所以我只有一个看起来像这样的视图:

<div>
     <h3><%= row.get('name') %></h3>
</div>

我不需要在ShowPropertyView中更改某些内容,我只是不确定是什么? 任何帮助将非常感激!谢谢。

1 个答案:

答案 0 :(得分:1)

我认为解决问题的最佳方法是将描述的功能分成两个视图。我真的建议使用backbone.js约定通过传递给它们的构造函数模型实例或集合实例like in docs来实现简单视图。

此解决方案的代码如下所示。首先查看一个模型

class OnePropertyView extends Backbone.View

  template: _.template($('#oneProperty').html())

  render: ->
    @model.fetch
      success: =>
        $('#propertyInfo').append(@template({model: @model}))

并为此模板:

<div>
    <h3><%= model.get('name') %></h3>
</div>

收集视图代码:

class CollectionPropertyView extends Backbone.View

  template: _.template($('#collectionProperty').html())

  render: ->
    @collection.fetch
      success: =>
        $('#propertyInfo').append(@template({collection: @collection}))

收集处理的模板:

<ul>
    <% collection.forEach(function (model) { %>
        <li><%= model.get('name') %></li>
    <% }); %>
</ul>

上面的代码可以像这样使用它,例如在router

model = new PropertyModel(id: modelId) # modelId retrived from URL
view = new OnePropertyView(model: model)
view.render()

和收集

collection = new PropertyCollection();
view = new CollectionPropertyView(collection: collection)
view.render()

有时,当集合视图有点复杂时,例如每行有一些操作,最好实现嵌套视图(表示行)。这种方法更简单,更易读,因为对于每一行,您都可以使用events mapping