LocalizedLabel.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. const i18n = require('LanguageData');
  2. // Returns a function, that, as long as it continues to be invoked, will not
  3. // be triggered. The function will be called after it stops being called for
  4. // N milliseconds. If `immediate` is passed, trigger the function on the
  5. // leading edge, instead of the trailing.
  6. function debounce(func, wait, immediate) {
  7. var timeout;
  8. return function() {
  9. var context = this, args = arguments;
  10. var later = function() {
  11. timeout = null;
  12. if (!immediate) func.apply(context, args);
  13. };
  14. var callNow = immediate && !timeout;
  15. clearTimeout(timeout);
  16. timeout = setTimeout(later, wait);
  17. if (callNow) func.apply(context, args);
  18. };
  19. }
  20. cc.Class({
  21. extends: cc.Component,
  22. editor: {
  23. executeInEditMode: true,
  24. menu: 'i18n/LocalizedLabel'
  25. },
  26. properties: {
  27. dataID: {
  28. get () {
  29. return this._dataID;
  30. },
  31. set (val) {
  32. if (this._dataID !== val) {
  33. this._dataID = val;
  34. if (CC_EDITOR) {
  35. this._debouncedUpdateLabel();
  36. } else {
  37. this.updateLabel();
  38. }
  39. }
  40. }
  41. },
  42. _dataID: ''
  43. },
  44. onLoad () {
  45. if(CC_EDITOR) {
  46. this._debouncedUpdateLabel = debounce(this.updateLabel, 200);
  47. }
  48. if (!i18n.inst) {
  49. i18n.init();
  50. }
  51. // cc.log('dataID: ' + this.dataID + ' value: ' + i18n.t(this.dataID));
  52. this.fetchRender();
  53. },
  54. fetchRender () {
  55. let label = this.getComponent(cc.Label);
  56. if (label) {
  57. this.label = label;
  58. this.updateLabel();
  59. return;
  60. }
  61. },
  62. updateLabel () {
  63. if (!this.label) {
  64. cc.error('Failed to update localized label, label component is invalid!');
  65. return;
  66. }
  67. let localizedString = i18n.t(this.dataID);
  68. if (localizedString) {
  69. this.label.string = i18n.t(this.dataID);
  70. }
  71. }
  72. });