具有复杂类型时,KnockoutJs中的值绑定无法进行选择 [英] value binding in KnockoutJs fails for select when having complex types

查看:97
本文介绍了具有复杂类型时,KnockoutJs中的值绑定无法进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在select元素上使用值绑定,如该小提琴中所述: http://jsfiddle.net /MikeEast/nM6dd/2/

I am trying to use the value binding on the select element, as described in this fiddle: http://jsfiddle.net/MikeEast/nM6dd/2/

但是,我似乎无法设置所选选项(值绑定).

However, I cannot seem to be able to set the selected option (value binding).

我知道我可以使用optionsValue绑定,但这会使该值成为字符串,而不是一个对象,这是不可取的.如果那是唯一的方法,我将如何确保将所选的选项写回到视图模型中?

I know I can use the optionsValue binding, but that makes the value a string instead of an object which is not preferable. If that is the only way to go, how would I do to ensure that the selected option is written back to the view model?

谢谢!

推荐答案

以下是解决方案.您必须将属性optionsValue: 'id'添加到数据绑定中. 您还必须在viewModel中放置一个返回所选对象的函数.

Here is the solution. You have to add the attribute optionsValue: 'id' to the data-bind. You also have to put a function in you viewModel that returns the selected object.

var viewModel = function() {
  this.items = ko.observableArray([
    { id: 1, name: "Apple" }, 
    { id: 2, name: "Orange"},
    { id: 3, name: "Banana"}
  ]);
  this.selectedItemId = ko.observable(3);
  this.selectedItem = function() {
    var self = this;
    return ko.utils.arrayFirst(this.items(), function(item) {
      return self.selectedItemId() == item.id;
    });
  }.bind(this);
};

var vm = new viewModel();
ko.applyBindings(vm);

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/1.2.1/knockout-min.js"></script>
<select data-bind="options: items, optionsText: 'name', optionsValue: 'id', value: selectedItemId"></select>
<span data-bind="text: selectedItem().name"></span>

干杯!

这篇关于具有复杂类型时,KnockoutJs中的值绑定无法进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆