在主干视图中填充选择列表数据的常见模式

Common pattern for populating select list data in Backbone views?

本文关键字:数据 列表 常见 模式 选择 填充 视图      更新时间:2023-09-26

My Backbone 应用程序具有多个视图,其中包含带有文本输入选择字段和复选框的表单。应使用我的 API 中的数据填充选择字段。给定的选择字段可以以多种不同的形式重复使用。

填充这些下拉列表的常用方法是什么?这是我一起操纵的解决方案...有没有更常见的方法?

一个可重用的选择字段,它填充自身...应用/视图/共享/location_selection.js:

define([
  'jquery',
  'backbone',
  'app/views/base',
  'app/collections/location'
], function($, Backbone, BaseView, LocationCollection) {
  'use strict';
  return BaseView.extend({
    initialize: function(options) {
      this.options = options || {};
      this.options.id = this.options.id || 'location';
      this.options.showBlank = typeof this.options.showBlank != 'undefined' ? this.options.showBlank : false;
      this.collection = new LocationCollection();
    },
    render: function() {
      this.setElement('<select id="' + this.options.id + '"></select>');
      var self = this;
      this.collection.fetch({
        success: function() {
          if (self.options.showBlank) {
            self.$el.append('<option></option');
          }
          self.collection.each(function(model) {
            self.$el.append('<option value="' + model.get('id') + '">' + model.get('name') + '</option>');
          });
        }
      });
      return this;
    }
  });
});

以及使用该视图的另一个视图中的代码片段:

render: function() {
  this.$el.html(this.template(this.model.toJSON()));
  var locationSelectionView = new LocationSelectionView({ showBlank: !this.model.get('id') });
  this.$('.location').append(locationSelectionView.render().el);
  return this;
},

和表单模板:

<form role="form">
  <div class="form-group">
    <label for="imei">IMEI</label>
    <input type="text" class="form-control" id="imei" value="{{data.imei}}" />
  </div>
  <div class="form-group location">
    <label for="location">Location</label>
  </div>
  <div class="checkbox">
    <label><input id="master" type="checkbox"{{#if master}} checked="checked"{{/if}} /> Master</label>
  </div>
</form>

如果您的项目视图和集合视图都有单独的模板,则可以通过以下方式执行此操作:

var ItemView = Backbone.View.extend({
    tagName: 'option',
    initialize:function(){        
        this.template= _.template($('#menu_item_view').html());    
    },    
    render:function(){        
        this.$el.html(this.template(this.model.toJSON()));        
        return this;        
    }
});
var CollectionView = Backbone.View.extend({
    tagName: 'select',
    initialize:function(){        
        this.collection = new ItemCollection();            
        this.collection.on('sync',this.render,this);            
        this.collection.fetch();
    },    
    render:function(){        
        _.each(this.collection.models,function( item ){            
            this.$el.append(new ItemView({model:item}).render().el );        
        },this);      
        return this;        
    }
});

编辑:请注意,在 Backbone 1.0 之前,当您调用 fetch 时,它用于触发"重置",但现在它会触发"同步",除非您编写 fetch({reset:true})。因此,根据您运行的 Backbone 版本,请注意这一点。