简体   繁体   English

我可以使用Backbone.ModelBinder将选择框选项文本绑定到模型吗?

[英]Can I bind a select box option text to a model using Backbone.ModelBinder?

I have an edit form set up in my Backbone app that populates with model data. 我在Backbone应用程序中设置了一个编辑表单,其中填充了模型数据。 I currently have it working without ModelBinder but want to switch over to ModelBinder. 我目前可以在没有ModelBinder的情况下使用它,但想切换到ModelBinder。

I have a select box where the value maps to an id in the model, and the selected option text should map to a string field on the model. 我有一个选择框,其中值映射到模型中的id,并且所选的选项文本应映射到模型上的字符串字段。 The user has the option of populating the model from the dropdown which will fill in the placeId and placeName or using a textbox to only fill in the placeName. 用户可以选择从下拉列表中填充模型,以填充placeId和placeName或使用文本框仅填充placeName。

My question is how do I get this - $("#placeName option:selected").text() into the placeName selector? 我的问题是如何将它- $("#placeName option:selected").text()放入placeName选择器?

Here is my model and bindings object: 这是我的模型和绑定对象:

// The Place Model
App.Models.Place = Backbone.Model.extend({
    defaults: {
          placeName: "",
          placeId: ""
  }
});

// Backbone Model Binder bindings
   bindings: {
       placeName:[
           {selector: '$("#placeName option:selected").text()'}, 
           {selector: '#textInputPlaceName'}] ,
    placeId:'[name=placeName]'
}

Here is the HTML. 这是HTML。 In the UI there is a checkbox for selecting either the dropdown or the input field 在用户界面中,有一个用于选择下拉列表或输入字段的复选框

<select id="placeName" name="placeName" class="inline">
        <option value="0" selected="selected"></option>
        <option value="444">exit 1</option>
        <option value="555">exit 2</option>
        <option value="666">exit 3</option>
</select>
<input id="textInputPlaceName" name="textInputPlaceName class="inline" disabled>

Here's the same code in a fiddle: http://jsfiddle.net/kDBvQ/ 这是小提琴中的相同代码: http : //jsfiddle.net/kDBvQ/

I ended up setting and retrieving the value in a function outside of the modelBinder bindings. 我结束了在modelBinder绑定之外的函数中设置和检索值。 I probably could have used a converter, but it was more simple to do it without. 我可能本可以使用转换器,但没有转换器则更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM