Game
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

util.js 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. window.reqAnimFrame = window.requestAnimationFrame || (function(fn) {
  2. return setTimeout(fn, 1000 / 60) });
  3. window.cancelAnimFrame = window.cancelAnimationFrame || window.clearTimeout;
  4. // Random number from min (inclusive) to max (exclusive)
  5. function randInt(min, max) {
  6. return Math.floor(Math.random() * (max - min)) + min;
  7. }
  8. function makeEventListener(obj) {
  9. obj.__callbacks = {};
  10. obj.on = makeEventListener.on;
  11. obj.off = makeEventListener.off;
  12. obj.once = makeEventListener.once;
  13. obj.emit = makeEventListener.emit;
  14. }
  15. makeEventListener.on = function on(name, fn) {
  16. if (!this.__callbacks[name])
  17. this.__callbacks[name] = [];
  18. this.__callbacks[name].push(fn);
  19. }
  20. makeEventListener.once = function once(name, fn) {
  21. var self = this;
  22. this.on(name, function f() {
  23. self.off(name, f);
  24. fn.apply(arguments);
  25. });
  26. }
  27. makeEventListener.off = function off(name, fn) {
  28. if (!this.__callbacks[name])
  29. return;
  30. for (var i in this.__callbacks[name]) {
  31. if (this.__callbacks[name] === fn)
  32. delete this.__callbacks[name][i];
  33. }
  34. }
  35. makeEventListener.emit = function emit(name) {
  36. if (!this.__callbacks[name])
  37. return;
  38. var args = [].slice.apply(arguments);
  39. args.splice(0, 1);
  40. this.__callbacks[name].forEach(function(f) {
  41. f.apply(args);
  42. });
  43. }