【问题标题】:Backbone Views inside Collections集合内的主干视图
【发布时间】:2012-09-03 22:14:57
【问题描述】:

我对骨干很陌生,需要用它来创建一个列表项。每个列表项都有一个模型和一个视图。因为它是一个列表,所以它似乎是收藏的理想解决方案,但我很难使用它们。

这是当前版本,我想将其更改为使用集合:

// The Model & view
var IntroModel = Backbone.Model.extend({});
var Introview = Backbone.View.extend({
    template: _.template( $('#taglist-intro').text() ),
    render: function() {
        console.log( this.model.attributes );
        this.$el.append( this.template( this.model.attributes ) );
    }
});

// We will store views in here
// Ideally this would be a collection
views = [];

// Get the data for that collection
$.getJSON( url, function( json ) {

    _.each( json, function( item ) {

        // Create each model & view, store views in the views array
        var model = new IntroModel( item );
        var view = new Introview({
        model : model
        })  
        views.push( view );

    })

})

// I can render a view like this
// But I'd rather it rendered the view when I add items to the collection
views[0].render()

所以我有什么作品,但它并没有真正做到“骨干方式”。这似乎有点毫无意义,因为:

  1. 最好使用集合,而不是数组
  2. 最好在将项目添加到数组时呈现视图
  3. 真的不是 Backbone..

感谢任何指点,如果您不能提供具体的代码示例,我仍然非常感谢涵盖此问题的链接和资源。

干杯,

理查德

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    您认为当前的实现不是 Backbone 方式的权利。您所做的大部分工作都是由骨干中的集合对象直接处理的。在主干中,集合本质上只是一个带有附加方法的数组。这些方法赋予了集合它们的力量。 Backbone 具有许多功能,包括:

    • 'url' 属性:使用此属性,当您运行 fetch 方法时,集合将自动填充(例如 myCollection.fetch() )。
    • 您可以将函数绑定到集合的“重置”事件。当您填充集合时会触发此事件。通过包含对集合的呈现事件的调用,您的集合可以在集合更改时自动呈现相关视图。还有其他收集事件(例如“添加”新模型等),您也可以将函数附加到这些事件。
    • 我发现 Backbone 文档是最好的起点。然而,一个简单的例子总是有用的。下面的代码展示了如何定义一个简单的集合,以及如何创建两个视图(一个视图创建列表,另一个视图呈现列表中的项目)。注意集合中 url 属性的使用。当您运行 fetch() 方法时,Backbone 使用它来检索集合的内容(请参阅 OrgListView 对象)。还要注意视图的渲染方法是如何绑定到集合的“重置”事件的,这样可以确保在填充集合后调用渲染事件(参见 OrgsListView 的初始化方法)。

              /**
           * Model
           */
          var Org = Backbone.Model.extend();
      
          /**
           * Collection
           */
          var Orgs = Backbone.Collection.extend({
              model: Org,
              url: '/orgs.json'
          });
      
          /**
           * View - Single Item in List
           */
          var OrgItemView = Backbone.View.extend({
              tagName: 'li',
              initialize: function() {
                  _.bindAll(this, 'onClick', 'render');
                  this.model = this.options.model;
                  // Create base URI component for links on this page. (e.g. '/#orgs/ORG_NAME')
                  this.baseUri = this.options.pageRootUri + '/' + encodeURIComponent(this.model.get('name'));
                  // Create array for tracking subviews.
                  /*var subViews = new Array();*/
              },
              events: {
                  'click a.test': 'onClick'
              },
              onClick: function(event) {
                  // Prevent default event from firing.
                  event.preventDefault();
                  if (typeof this.listContactsView === 'undefined') {
                      // Create collection of contacts.
                      var contacts = new ContactsByOrg({ url: '/orgs.json/' + encodeURIComponent(this.model.get('name')) });
                      this.listContactsView = new ListContactsView({ collection: contacts, baseUri: this.baseUri });
                      this.$el.append(this.listContactsView.render().el);
                  }
                  else {
                      // Close View.
                      this.listContactsView.close();
                      // Destroy property this.listContactsView.
                      delete this.listContactsView;
                  }
              },
              onClose: function() {
      //      console.log('Closing OrgItemView');
              },
              render: function() {
                  // TODO: set proper value for href. Currently using a dummy placeholder
                  this.$el.html('<a class="test" href="' + this.baseUri + '">' + this.model.get('name') + '</a>');
                  return this;
              }
          });
      
          /**
           * View - List of organizations
           */
          var OrgsListView = Backbone.View.extend({
              className: 'orgs-list',
              initialize: function() {
                  console.log('OrgsListView');
                  _.bindAll(this, 'render');
                  this.pageRootUri = this.options.pageRootUri;
                  this.collection = this.options.collection;
                  // Bind render function to collection reset event.
                                      this.collection.on('reset', this.render);
                  // Populate collection with values from server.
                  this.collection.fetch();
              },
              onClose: function() {
                  this.collection.off('reset', this.render);
      //      console.log('Closing OrgsListView');
              },
              render: function() {
                  var self = this;
                  this.$el.html('<ul></ul>');
                  this.collection.each(function(org, index) {
                      var orgItemView = new OrgItemView({ model: org, pageRootUri: self.pageRootUri });
                      self.$('ul').append(orgItemView.render().el);
                  });
                  return this;
              }
          });
      

    【讨论】:

    • 如果你愿意,你可以有这个简单的例子:jsfiddle.net/ambiguous/fHUcu你说的和我想说的差不多。
    • 非常感谢你们。感谢我的问题有点新手,所以我非常感谢您提供如此详细的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-31
    • 1970-01-01
    相关资源
    最近更新 更多