knockoutjs:Example 3: 親の親の値を使う(?):The custom binding Control descendant bindings

  1. <!DOCTYPE html>
  2. <html lang="ja">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>knockoutjs:Example 3: 親の親の値を使う(?):The custom binding Control descendant bindings</title>
  6. <script type="text/javascript" src="jquery-1.5.1.min.js"></script>
  7. <script type="text/javascript" src="knockout-2.1.0beta.js"></script>
  8. </head>
  9. <body>
  10. <h1>Example 3: 親の親の値を使う(?):The custom binding Control descendant bindings</h1>
  11. <div data-bind="withProperties: { displayMode: 'twoColumn' }">
  12.   The outer display mode is <span data-bind="text: displayMode"></span>.
  13.   <div data-bind="withProperties: { displayMode: 'doubleWidth' }">
  14.     The inner display mode is <span data-bind="text: displayMode"></span>, but I haven't forgotten
  15.     that the outer display mode is <span data-bind="text: $parentContext.displayMode"></span>.
  16.   </div>
  17. </div>
  18. <script type="text/javascript">
  19. ko.bindingHandlers.withProperties = {
  20.   init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  21.     // Make a modified binding context, with a extra properties, and apply it to descendant elements
  22.     var newProperties = valueAccessor(),
  23.         childBindingContext = bindingContext.createChildContext(viewModel);
  24.     ko.utils.extend(childBindingContext, newProperties);
  25.     ko.applyBindingsToDescendants(childBindingContext, element);
  26.     
  27.     // Also tell KO *not* to bind the descendants itself, otherwise they will be bound twice
  28.     return { controlsDescendantBindings: true };
  29.   }
  30. };
  31. var viewModel = {};
  32. ko.applyBindings(viewModel);
  33. </script>
  34. <div style="font-size:10pt;text-align:right;margin-top:0.5em;">
  35. <a href="//tips.recatnap.info/" target="_top">PCスキルの小技・忘却防止メモ</a> -
  36. <a href="//tips.recatnap.info/wiki/" target="_top">PCスキルの小技・忘却防止メモのまとめ(wiki)</a>
  37. </div>
  38. <div style="font-size:10pt;text-align:center;margin-top:0.5em;padding:0.5em;border-top:1px solid #ccc;">
  39. Copyright &copy; 2009 by PCスキルの小技・忘却防止メモ. All rights reserved.
  40. </div>
  41. </body>
  42. </html>