【问题标题】:Placeholder in Select that uses Backbone CollectionSelect 中使用 Backbone 集合的占位符
【发布时间】:2012-08-07 18:51:39
【问题描述】:

我有一个通过主干集合填充的选择框:

class Prog.Views.History extends Backbone.View

  template: JST['backbone/templates/shapes/history']
  tagName: "option"


  initialize: ->
    @model.bind('change:formatted', @render, this);

  render: ->
   $(@el).html(@template(history: @model))
   this

主干/模板/形状/历史

<option value="<%=history.get('origin')%>"><%=history.get('origin')%></option>

这很好用,所有正确的数据都显示在选择框中,但我希望第一个选项是“请选择”,即占位符...我考虑注入一条名为“占位符”的记录进入收藏,但它似乎是一个迂回的方式。

我是这样称呼它的:

  appdenDropdown: (history) ->
    console.log("append trigger")
    view = new Prog.Views.History(model: history)
    $('select#history').append(view.render().el)

我怎样才能默认这个?

【问题讨论】:

    标签: backbone.js


    【解决方案1】:

    首先我认为这个实现不能正常工作,我认为渲染的结果会是这样的:

    <option><option value="the_origin">the_origin</option></option>
    

    注意双重选项

    一个适当的解决方案可能是这样的:

    class Prog.Views.History extends Backbone.View
      tagName: "option"
    
      initialize: ->
        @model.bind('change:formatted', @render, this);
    
      render: ->
        $(@el).attr( "value", this.get( "origin" ) )
        $(@el).html( this.get("origin") )
        this
    

    这里不需要模板。

    关于包含“请选择”选项

    将直接在 HTML 中硬编码的 “请选择”选项元素包含到 select 元素中。

    然后不要使用this.$el.html() 来填充select 而是this.$el.append(),这将尊重实际的默认选项,它会在其后添加动态元素。

    更新

    例如,如果您的 select 元素 看起来像这样:

    <select id="history"></select>
    

    让它看起来像这样:

    <select id="history">
      <option value="0" selected="selected">Please select...</option>
    </select>
    

    当您使用append 添加动态选项元素时,占位符选项元素将保留。

    【讨论】:

    • 您介意在应用程序上添加占位符来更新您的示例吗?
    • 为此,我需要您使用呈现完整 select 元素的代码更新问题,并使用 Traveltime.Views.History 子视图呈现 选项元素。准备好后在此线程中发出信号。
    猜你喜欢
    • 1970-01-01
    • 2022-12-04
    • 2020-02-26
    • 2019-06-17
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2015-02-07
    • 2014-08-03
    相关资源
    最近更新 更多