如何为knockout observable分配本地值

时间:2014-05-12 08:25:43

标签: javascript knockout.js

我想知道有没有办法将局部变量分配给knockout变量?

例如说视图模型是:

 var index = $("#country :selected").text();
 var viewmodel = {
    CountriesList : ko.observableArray([]),
    CountryId: ko.observable(),
    Text: ko.observable(index)    

 }

查看是:

<select id="country" data-bind="options: $parent.CountriesList ,optionsText: 'CountryName',optionsValue:'CountryId',value:CountryId,optionsCaption: 'Select Country..'"
            style="width: 148px">
 </select>

请有人帮助我如何获得optionsText下拉值? 我的CountriesList是一个可观察的数组,它会获得(CountryName:'india',CountryId:'1') *样本等值。

1 个答案:

答案 0 :(得分:0)

这里有两个示例,您可以获得optionsText

  1. CountryId绑定,因此绑定value包含适当的CountryId
  2. CountryName绑定,因此绑定value包含目标CountryName
  3. HTML

    Binding on CountryId: <select id="country" data-bind="options: CountriesList ,optionsText: 'CountryName', optionsValue:'CountryId', value: CountryId, optionsCaption: 'Select Country..'"style="width: 148px"></select>
    
    <br/>
    
    Binding on CountryName: <select id="country" data-bind="options: CountriesList ,optionsText: 'CountryName', optionsValue:'CountryName', value: CountryName, optionsCaption: 'Select Country..'"style="width: 148px"></select>
    

    的JavaScript

    var countries = [
        { "CountryName": "India1", "CountryId": "1" },
        { "CountryName": "India2", "CountryId": "2" },
        { "CountryName": "India3", "CountryId": "3" }
    ]; 
    
    var ViewModel = function(){
        var self = this;
        self.CountriesList = ko.observableArray(countries);
        self.CountryId = ko.observable();
        self.CountryName = ko.observable();
    
        self.CountryId.subscribe(function(newValue) {
            if(newValue){
                var index = newValue - 1; //because "Select Country.." is the first item
                alert(countries[index].CountryName);
            }
        }, this);
    
        self.CountryName.subscribe(function(newValue) {
            if(newValue){
                alert(newValue);
            }
        }, this);
    };
    
    ko.applyBindings(new ViewModel);
    

    您可以使用代码here