knockoutjs:Example 4: hasFocusbバインディングの拡張:The custom binding

  1. <!DOCTYPE html>
  2. <html lang="ja">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>knockoutjs:Example 4: hasFocusbバインディングの拡張:The custom binding</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 4: hasFocusbバインディングの拡張:The custom binding</h1>
  11. <p>Name: <input data-bind="hasFocus: editingName" /></p>
  12.  
  13. <!-- Showing that we can both read and write the focus state -->
  14. <div data-bind="visible: editingName">You're editing the name</div>
  15. <button data-bind="enable: !editingName(), click:function() { editingName(true) }">Edit name</button>
  16. <script type="text/javascript">
  17. ko.bindingHandlers.hasFocus = {
  18.   init: function(element, valueAccessor)
  19.   {
  20.     $(element).focus(function()
  21.     {
  22.       var value = valueAccessor();
  23.       value(true);
  24.     });
  25.     $(element).blur(function()
  26.     {
  27.       var value = valueAccessor();
  28.       value(false);
  29.     });
  30.   },
  31.   update: function(element, valueAccessor)
  32.   {
  33.     var value = valueAccessor();
  34.     if (ko.utils.unwrapObservable(value))
  35.       element.focus();
  36.     else
  37.       element.blur();
  38.   }
  39. };
  40. var viewModel = {
  41.   editingName: ko.observable()
  42. };
  43. ko.applyBindings(viewModel);
  44. </script>
  45. <div style="font-size:10pt;text-align:right;margin-top:0.5em;">
  46. <a href="//tips.recatnap.info/" target="_top">PCスキルの小技・忘却防止メモ</a> -
  47. <a href="//tips.recatnap.info/wiki/" target="_top">PCスキルの小技・忘却防止メモのまとめ(wiki)</a>
  48. </div>
  49. <div style="font-size:10pt;text-align:center;margin-top:0.5em;padding:0.5em;border-top:1px solid #ccc;">
  50. Copyright &copy; 2009 by PCスキルの小技・忘却防止メモ. All rights reserved.
  51. </div>
  52. </body>
  53. </html>