javascript 在 Backbone 视图中填充选择列表数据的常见模式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18900686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:37:33  来源:igfitidea点击:

Common pattern for populating select list data in Backbone views?

javascriptformsbackbone.jshtml-select

提问by Chad Johnson

My Backbone app has several views containing forms with text inputs select fields, and checkboxes. The select fields should be populated using data from my API. A given select field may be reused in multiple different forms.

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

What's a commonly-used approach for populating these dropdowns? Here's a solution I've rigged together...is there a more common approach?

填充这些下拉菜单的常用方法是什么?这是我组合在一起的解决方案......有没有更常见的方法?

A reusable select field which populates itself...app/views/shared/location_selection.js:

一个可重复使用的选择字段,它会自动填充...app/views/shared/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;
    }
  });
});

And a snippet from another view which uses that view:

以及来自使用该视图的另一个视图的片段:

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;
},

And the form template:

和表单模板:

<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>

回答by redconservatory

If you have separate templates for both your item view and collection view you can do it this way:

如果您的项目视图和集合视图都有单独的模板,您可以这样做:

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;        
    }
});

Edit: just as a note, before Backbone 1.0 when you called fetch it use to trigger 'reset' but now it triggers 'sync' unless you write fetch({reset:true}). So depending on the version of Backbone you are running, be aware of that.

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