KnockOutJS中的ViewModel可访问性

时间:2014-09-03 12:26:19

标签: javascript knockout.js

为什么在警报消息中无法访问viewModel.availableCountries()?这段代码出了什么问题?

<form id="form1" runat="server">
    <div>
    Select the car: 
    <select ></select>
     <script type="text/javascript">
         alert('The length of the array is ' + viewModel.availableCountries().length);
      </script>
    </div>
        <script type="text/javascript">
            var viewModel = {
                availableCountries: ko.observableArray(['France', 'Germany', 'Spain']),
                chosenCountries: ko.observableArray(['Germany']) // Initially, only Germany is selected
            };
            viewModel.chosenCountries.push('France');
            ko.applyBindings(viewModel);
        </script>
    </form>

1 个答案:

答案 0 :(得分:1)

就像@ haim770已经说过的那样,你的代码顺序是错误的。您在创建viewModel之前正在访问它。

将其更改为以下内容,它应该可以正常工作:

<form id="form1" runat="server">
    <div>
    Select the car: 
    <select ></select>
    </div>
        <script type="text/javascript">
            var viewModel = {
                availableCountries: ko.observableArray(['France', 'Germany', 'Spain']),
                chosenCountries: ko.observableArray(['Germany']) // Initially, only Germany is selected
            };
            viewModel.chosenCountries.push('France');
            ko.applyBindings(viewModel);
            alert('The length of the array is ' + viewModel.availableCountries().length); // Moved this line down
        </script>
    </form>