ko.dataFor()是否可以与`select`元素一起使用? [英] Does ko.dataFor() work with `select` elements?

查看:51
本文介绍了ko.dataFor()是否可以与`select`元素一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在select元素上使用ko.dataFor(),但是它返回了整个ViewModel.我期望得到选定的option的对象,但是我总是得到ViewModel.我尝试传递selectoption,但是无论哪种方式,我都得到相同的结果.

I'm trying to use ko.dataFor() on a select element but it's returning the whole ViewModel. I'm expecting to get the object of the selected option, but I always get the ViewModel instead. I've tried passing the select and the option but either way I get the same result.

http://jsfiddle.net/LzAAB/3/

<select id="companies" data-bind="options: companies, optionsText: 'name', optionsValue: 'id', optionsCaption: ' ' "></select>
<br/>
ko.DataFor(select)<br/>
<textarea id="a" cols="40" rows="10"></textarea>
<br/>
ko.DataFor(option)<br/>
<textarea id="b" cols="40" rows="10"></textarea>
<br/>
<div data-bind="text: ko.toJSON($root)"></div>


function MyViewModel() {
    var self = this;
    self.companies = ko.observableArray([{id:1, name: "Chevy"},{id:2, name: "Ford"}, {id:2, name: "Dodge"}]);
    self.countries = ko.observableArray([{id:1, name: "USA"},{id:2, name: "Canada"}, {id:2, name: "Mexico"}]);
}

var vm = new MyViewModel();

ko.applyBindings(vm);

$("#companies").change(function(){    
    $("#a").val("dataFor("+this.id+"):"+  ko.toJSON(ko.dataFor(this)));

    var selectedOption = $(this).find(":selected")[0];
    $("#b").val("dataFor("+this.id+"):"+  ko.toJSON(ko.dataFor(selectedOption)));
});

推荐答案

ko.dataFor()函数为您提供的内容是元素绑定到的对象.如果访问$data上下文变量,则绑定将是与该对象相同的对象. options绑定生成的选项元素使用相同的上下文,因此您不会在此看到任何差异.它仅与更改绑定上下文(例如,在foreach绑定中)的绑定有关.

What the ko.dataFor() function gives you is the object for which an element is binding to. It's the same object your bindings would see if you accessed the $data context variable. The option elements generated by the options binding uses the same context so you won't see any difference there. It's only relevant to bindings where the binding context is changed (e.g., in a foreach binding).

如果您使用敲除功能来访问所需的对象而不是依赖于jquery,那会更好.创建一个可观察对象,并将该值绑定到选择对象.然后,您可以使用选定的值进行所需的操作.

It would be better if you used knockout's features to access the objects you want instead of relying on jquery. Create an observable and bind the value to the select. Then you can do what you want with the selected value.

function MyViewModel() {
    var self = this;
    self.selectedCompany = ko.observable();
    self.companies = ko.observableArray(...);
    self.countries = ko.observableArray(...);
}

<select id="companies"
        data-bind="value: selectedCompany,
                   options: companies,
                   optionsText: 'name',
                   optionsCaption: ' '">
</select>
<br/>
Selected<br/>
<textarea cols="40" rows="10" data-bind="text: ko.toJSON(selectedCompany)">
</textarea>

更新了小提琴

这篇关于ko.dataFor()是否可以与`select`元素一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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