keynav.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. Ext.require([
  2. 'Ext.XTemplate',
  3. 'Ext.util.KeyNav',
  4. 'Ext.fx.*'
  5. ]);
  6. Ext.define('Board', {
  7. constructor: function(size, activeCls){
  8. this.size = size;
  9. this.activeCls = activeCls;
  10. },
  11. render: function(el){
  12. el = Ext.get(el);
  13. var tpl = Ext.create('Ext.XTemplate',
  14. '<tpl for=".">',
  15. '<div class="square">{.}</div>',
  16. '<tpl if="xindex % ' + this.size + ' === 0"><div class="x-clear"></div></tpl>',
  17. '</tpl>'),
  18. data = [],
  19. i = 0,
  20. max = this.size * this.size;
  21. for (; i < max; ++i) {
  22. data.push(i + 1);
  23. }
  24. tpl.append(el, data);
  25. this.cells = el.select('.square');
  26. },
  27. getIndex: function(xy){
  28. return this.size * xy[0] + xy[1];
  29. },
  30. constrain: function(x, y) {
  31. x = Ext.Number.constrain(x, 0, this.size - 1);
  32. y = Ext.Number.constrain(y, 0, this.size - 1);
  33. return [x, y];
  34. },
  35. setActive: function(x, y) {
  36. var xy = this.constrain(x, y),
  37. cell = this.cells.item(this.getIndex(xy));
  38. cell.radioCls(this.activeCls);
  39. this.active = xy;
  40. },
  41. setActiveCls: function(activeCls){
  42. this.cells.removeCls(this.activeCls);
  43. this.activeCls = activeCls;
  44. var active = this.active;
  45. this.setActive(active[0], active[1]);
  46. },
  47. highlightActive: function(){
  48. var cell = this.cells.item(this.getIndex(this.active));
  49. Ext.create('Ext.fx.Anim', {
  50. target: cell,
  51. duration: 1000,
  52. alternate: true,
  53. iterations: 2,
  54. to: {
  55. backgroundColor: '#FFFF00'
  56. },
  57. callback: function(){
  58. cell.setStyle('background-color', '');
  59. }
  60. });
  61. },
  62. moveUp: function(){
  63. var active = this.active;
  64. this.setActive(active[0] - 1, active[1]);
  65. },
  66. moveDown: function(){
  67. var active = this.active;
  68. this.setActive(active[0] + 1, active[1]);
  69. },
  70. moveLeft: function(){
  71. var active = this.active;
  72. this.setActive(active[0], active[1] - 1);
  73. },
  74. moveRight: function(){
  75. var active = this.active;
  76. this.setActive(active[0], active[1] + 1);
  77. }
  78. });
  79. Ext.onReady(function(){
  80. var cls = 'active-green';
  81. var board = new Board(4, cls);
  82. board.render('board');
  83. board.setActive(0, 0);
  84. var nav = Ext.create('Ext.util.KeyNav', Ext.getDoc(), {
  85. scope: board,
  86. left: board.moveLeft,
  87. up: board.moveUp,
  88. right: board.moveRight,
  89. down: board.moveDown,
  90. space: board.highlightActive,
  91. home: function(){
  92. cls = Ext.String.toggle(cls, 'active-green', 'active-red');
  93. board.setActiveCls(cls);
  94. }
  95. });
  96. });