WinJS双向绑定返回undefined

时间:2014-01-17 06:47:28

标签: data-binding winjs

我是window8开发的新手,我基本上都是尝试实现这个链接 http://msdn.microsoft.com/en-us/magazine/jj651576.aspx 我在链接示例中使用了如图8中的视图模型,但是我无法显示数据,它显示了undefine,但是如果我只给出一个数组元素,我就可以绑定它。

我的用户界面是

<body>
   <section aria-label="Main content" role="main">
      <!-- display each person -->
      <div id="nameLabel">Name</div>
      <input id="name" readonly="true" type="text" data-win-bind="value: name" />
      <div id="ageLabel">Age</div>
      <input id="age" readonly="true" type="text" data-win-bind="value: age" />
      <div id="colorLabel">Favorite Color</div>
      <div id="color" data-win-bind="style.backgroundColor:favoriteColor"></div>
      <div id="buttons">
        <button id="previousButton"></button>
        <button id="birthdayButton"></button>
        <button id="nextButton"></button>
      </div>
    </section>
</body>

并且JavaScript包含

 var people = [
      // Notify binding listeners when these objects change
      WinJS.Binding.as({ name: "John", age: 18, favoriteColor: "red" }),
      WinJS.Binding.as({ name: "Tom", age: 16, favoriteColor: "green" }),
      WinJS.Binding.as({ name: "Chris", age: 42, favoriteColor: "blue" }),
            ];
            // Bind the current person to the HTML elements in the section
            var section = document.querySelector("section[role=main]");
            var current = 0;
            var viewModel = WinJS.Binding.as({ person: people[current+1] });
            WinJS.Binding.processAll(section, viewModel);
            nextButton.onclick = function () {
                current = (people.length + current + 1) % people.length;
                viewModel.person = people[current];
            };

结果如下:

binding result

请帮我将UI与数据模型绑定。提前谢谢。

1 个答案:

答案 0 :(得分:1)

问题出现是因为您已将personWinJS.Binding双重包裹在一起。执行此操作时,需要将属性路径更改为:

data-win-bind="value: person.name"

创建viewModel属性时,它创建了一个包含实际person实例的新属性:

var viewModel = WinJS.Binding.as({ person: people[current+1] });

另外,请注意WinJs中没有双向绑定。