knockoutjs:Example 2: 親で指定したものを子・孫に使う:The custom binding Control descendant bindings

  1. <!DOCTYPE html>
  2. <html lang="ja">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>knockoutjs:Example 2: 親で指定したものを子・孫に使う: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 2: 親で指定したものを子・孫に使う:The custom binding Control descendant bindings</h1>
  11. <div data-bind="withProperties: { emotion: 'happy' }">
  12.     Today I feel <span data-bind="text: emotion"></span>. <!-- Displays: happy -->
  13. </div>
  14. <div data-bind="withProperties: { emotion: 'whimsical' }">
  15.     Today I feel <span data-bind="text: emotion"></span>. <!-- Displays: whimsical -->
  16. </div>
  17. <script type="text/javascript">
  18. ko.bindingHandlers.withProperties = {
  19.   init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
  20.     // Make a modified binding context, with a extra properties, and apply it to descendant elements
  21.     var newProperties = valueAccessor(),
  22.         innerBindingContext = bindingContext.extend(newProperties);
  23.     ko.applyBindingsToDescendants(innerBindingContext, element);
  24.     
  25.     // Also tell KO *not* to bind the descendants itself, otherwise they will be bound twice
  26.     return { controlsDescendantBindings: true };
  27.   }
  28. };
  29. var viewModel = {};
  30. ko.applyBindings(viewModel);
  31. </script>
  32. <div style="font-size:10pt;text-align:right;margin-top:0.5em;">
  33. <a href="//tips.recatnap.info/" target="_top">PCスキルの小技・忘却防止メモ</a> -
  34. <a href="//tips.recatnap.info/wiki/" target="_top">PCスキルの小技・忘却防止メモのまとめ(wiki)</a>
  35. </div>
  36. <div style="font-size:10pt;text-align:center;margin-top:0.5em;padding:0.5em;border-top:1px solid #ccc;">
  37. Copyright &copy; 2009 by PCスキルの小技・忘却防止メモ. All rights reserved.
  38. </div>
  39. </body>
  40. </html>