简体   繁体   English

如何在 BackboneJS 中显示 Model 属性的 select 列表(下拉列表)?

[英]How can I display a select list (dropdown) for a Model property in BackboneJS?

I am trying to build a simple contact editor application in Backbone.js and I have run into a bit of an issue that I don't know how to solve because I'm not familiar with Backbone.js yet.我正在尝试在 Backbone.js 中构建一个简单的联系人编辑器应用程序,但我遇到了一些我不知道如何解决的问题,因为我还不熟悉 Backbone.js。

I have a Model Contact and that item has a field ProductLineID (each Contact has a Product Line that it is associated with).我有一个 Model Contact ,该项目有一个ProductLineID字段(每个联系人都有一个与之关联的产品线)。 In displaying the editor for this Contact I would like to display a dropdown list with the possible ProductLine options and have it preset to the current value.在显示此联系人的编辑器时,我想显示一个下拉列表,其中包含可能的 ProductLine 选项并将其预设为当前值。 How would I do that in Backbone.js?我将如何在 Backbone.js 中做到这一点?

I know how to do it in knockout.js with data-binding:我知道如何在 knockout.js 中进行数据绑定:

<select id="ProductLineID" name="ProductLineID"
        data-bind="options: productLineOptions, 
        optionsValue: 'ID', 
        optionsText: 'Name', 
        value: ProductLineID, 
        optionsCaption: 'All'">
</select>

In this example productLineOptions is a JSON object that is already preloaded on the page.在此示例中,productLineOptions 是已在页面上预加载的 JSON object。

That would accomplish precisely what I want, but I don't know how to do the equivalent in Backbone.js.这将完全实现我想要的,但我不知道如何在 Backbone.js 中做同样的事情。

I can provide more code from my actual example, but this seems like it's a bit of a trivial example and does not require specific code.我可以从我的实际示例中提供更多代码,但这似乎是一个微不足道的示例,不需要特定代码。

Something like the following would work if you used the underscore templates :如果您使用下划线模板,则类似以下内容会起作用:

<select id="ProductLineID" name="ProductLineID">
    <option value="">--select a product line--</option>
    <% _(productLineOptions).each(function(pl) { %>
      <option value="<%= pl.ID %>"><%= pl.Name %></option>
    <% }); %>
</select>

And then you would just have to make sure that you passed in the productLineOptions object into the template's context.然后您只需确保将productLineOptions传递到模板的上下文中。

Backbone.js does not do databinding out of the box, like Knockout does. Backbone.js 不像 Knockout 那样开箱即用地进行数据绑定。 It leaves that aspect up to the developer to do however they wish.它将这方面留给开发人员按照他们的意愿去做。 The basic way is to set up event listeners for changes.基本方法是为更改设置事件侦听器。

If you do want to do knockout-style databinding, there's a project which may support what you need.如果你确实想做淘汰赛风格的数据绑定,有一个项目可以支持你所需要的。

https://github.com/derickbailey/backbone.modelbinding https://github.com/derickbailey/backbone.modelbinding

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

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