什么$ context和$ data完全是在淘汰赛?

时间:2014-05-19 18:01:13

标签: javascript html knockout.js

我无法理解knockout.js中特殊属性$ data和$ context之间的区别。

当使用pager.js更改绑定上下文时,我必须指定with: $context以使我的可观察属性可达,这对我来说听起来不正常。

鉴于JS:

pager.useHTML5history = true;
pager.Href5.history = History;

var App = {};

App.user = {
  name: ko.observable('Me'),
  student: ko.observable(false)
};

App.user.setup = {
  setStudent: function() {
    App.user.student(true)
  }
};

pager.extendWithPage(App);

ko.applyBindings(App);
pager.startHistoryJs();

此HTML 有效

<p><a href="#" data-bind="page-href: 'user/setup/role'">Role setup</a></p>
<div data-bind="page: {id: 'user', with: user, role: 'start'}" class="container">
  <div data-bind="page: {id: 'setup', with: setup}">
    <div data-bind="page: {id: 'role', with: $context}">
      <h2><strong data-bind="text: $parent.name"></strong>, are you a student ?</h2>
      <button data-bind="click: $context.setStudent">I am a student</button>
    </div>
  </div>
</div>

此HTML 无效setStudent显示为未定义,因为我删除了前面的$context

<p><a href="#" data-bind="page-href: 'user/setup/role'">Role setup</a></p>
<div data-bind="page: {id: 'user', with: user, role: 'start'}" class="container">
  <div data-bind="page: {id: 'setup', with: setup}">
    <div data-bind="page: {id: 'role', with: $context}">
      <h2><strong data-bind="text: $parent.name"></strong>, are you a student ?</h2>
      <button data-bind="click: setStudent">I am a student</button>
    </div>
  </div>
</div>

此HTML 无法正常工作,不会弹出错误,但名称仍为空白:

<p><a href="#" data-bind="page-href: 'user/setup/role'">Role setup</a></p>
<div data-bind="page: {id: 'user', with: user, role: 'start'}" class="container">
  <div data-bind="page: {id: 'setup', with: setup}">
    <div data-bind="page: {id: 'role'}">
      <h2><strong data-bind="text: $parent.name"></strong>, are you a student ?</h2>
      <button data-bind="click: setStudent">I am a student</button>
    </div>
  </div>
</div>

同样,我知道我可能在$context的概念中遗漏了一些东西。我认为它引用了整个ViewModel,包括其中定义的数据。但显然它不是。

谢谢!

0 个答案:

没有答案