访问JavaScript数组的元素

时间:2015-11-18 01:13:33

标签: javascript mvvm knockout.js

我在查看模型中访问模型对象时遇到了一些问题。这可能只是一个JavaScript / KnockoutJS熟悉问题,所以任何帮助都表示赞赏。这是我的代码:

<!-- VIEW -->
<select data-bind="options: allTypes, 
                   optionsCaption: 'Choose...',                   
                   value: chosenType"></select>
<div data-bind="text: chosenType"></div>
<div data-bind="text: chosenValues"></div> <!-- << This line not working -->
<script type="text/javascript">

/*-- VIEW MODEL --*/
function ViewModel() {
    this.chosenType=ko.observable();
    this.chosenValues=allValues[this.chosenType]; // <-- Problem here?
}

/*-- MODEL --*/
var allTypes=["Animals","Plants","Minerals"];
var allValues={
    "Animals":["Pig","Big pig","Owl"],
    "Plants":["Aloe","Fern"],
    "Minerals":["Bauxite","Chromite"]
    };

    ko.applyBindings(new ViewModel());
</script>

我认为问题可能在于如何声明this.chosenValues。谢谢你的阅读。

1 个答案:

答案 0 :(得分:1)

文本绑定仅适用于单个值,不适用于集合/数组。 您可以使用 foreach 绑定列出每个项目,例如

<div data-bind="foreach: chosenValues">
    <span data-bind="text: $data"></span>
</div>

或者您可以使用computedObservable即

function ViewModel() {
   this.chosenType=ko.observable();
   // computed value is evaluated if an observable value changes
   // this creates a comma separated string of values
   // you'll probably want safety checks here but just a quick sample
   this.chosenValues=ko.computed(function() {
        var chosenVals=allValues[this.chosenType()];
        return chosenVals.join(', ');
   }, this);
}

还记得从模型更新UI,您需要某种形式的可观察。在您的示例中, chosenValues 不是可观察的,因此如果选择更改,则不会更新UI。

另请参阅https://jsfiddle.net/51oufny4/了解工作样本

修改 ** 以下是上述小提琴中提供的示例:

<!-- VIEW -->
<select data-bind="options: allTypes, 
               optionsCaption: 'Choose...',                   
               value: chosenType"></select>
<div data-bind="text: chosenType"></div>
<div data-bind="text: chosenValues"></div>
<script type="text/javascript">

/*-- VIEW MODEL --*/
function ViewModel() {
    this.chosenType=ko.observable();
    this.chosenValues=ko.computed(function(){
        return allValues[this.chosenType()];
    }, this);
}

/*-- MODEL --*/
var allTypes=["Animals","Plants","Minerals"];
var allValues={
    "Animals":["Pig","Big pig","Owl"],
    "Plants":["Aloe","Fern"],
    "Minerals":["Bauxite","Chromite"]
};

ko.applyBindings(new ViewModel());
</script>