在itemview中显示Backbone模型嵌套属性

时间:2014-06-12 13:39:39

标签: javascript backbone.js marionette

最初是我的Backbone模型

 [
   {
        "id" : 1,
    "author" : "CA",
    "city": "LA",
        "Num_of_books": "5"
   },

   {
        "id": 2,
    "author":"John",   
    "city": "AM",
    "Num_of_books": "10"
   }
 ]

我将集合传递给布局视图,该视图具有复合视图,复合视图中的项目视图就像

 var View = Backbone.Marionette.ItemView.extend({
    tagName: 'option',
    constructor: function(options) {
        this.attributes = {
            value: options.model.id
        };
        console.log(options);
        Backbone.Marionette.ItemView.prototype.constructor.apply(this, arguments);
    },
    template: _.template("<%= author %>")
 });

这给了我一个

   <option value="idValue"> Author Name </option>

现在我需要将我的json格式更改为嵌套(对象而不是数组),因此id是关键。例如

  {
       "1": {
        "author" : "CA",
    "city": "LA",
        "Num_of_books": "5"
       },

       "2": {
        "author":"John",   
    "city": "AM",
    "Num_of_books": "10"
      }
  }

现在我如何在项目视图中访问我的模型属性,这样我就能实现像

这样的东西
  <option value="idValue"> Author Name </option>

1 个答案:

答案 0 :(得分:0)

理想情况下,此数据应该是集合,而不是模型。以这种方式使用它违背了Backbone&amp; amp;木偶会在以后引起各种可维护性问题。

考虑这样的事情:

var Book = Backbone.Model.extend({
    // .. book model config
});

var BookShelf = Backbone.Collection.extend({
    model: Book
});

var BookOption = Marionette.ItemView.extend({
    tagName: 'option',
    template: _.template('<%= author %>'),
    attributes: function() {
       return {
         value: this.model.id
       }
    }
});

var BookList = Marionette.CollectionView.extend({
    tagName: 'select',
    itemView: BookOption
});

// ------ 

var bookshelf = new BookShelf();

bookshelf.add([{
    "id": 1,
        "author": "CA",
        "city": "LA",
        "Num_of_books": "5"
},{
    "id": 2,
        "author": "John",
        "city": "AM",
        "Num_of_books": "10"
}]);

var bookList = new BookList();