Да, вы можете использовать класс singleton в Extjs для вашего приложения. Когда вы создаете свой Utilities
внутри, вам нужно установить config singleton:true
. Если задано значение true, класс будет создан как singleton. Например:
Ext.define('Logger', {
singleton: true,
log: function(msg) {
console.log(msg);
}
});
Logger.log('Hello');
Вы можете проверить здесь с рабочей Sencha fiddle demo. Это всего лишь небольшая демонстрация, которую вы можете реализовать в своем приложении. А также вы можете посетить здесь проект ExtJS gitlab с утилитой класса sigletone
Фрагмент кода
Ext.application({
name: 'Fiddle',
launch: function () {
//This sigletone class will accesible througout the app via using the
//Name {AppConstants( whatever name your provide you can access with the same name)}
//{singleton: true,} When set to true, the class will be instantiated as singleton.
Ext.define('AppConstants', {
alternateClassName: 'AppConstants',
singleton: true,
config: {
userId: '1'
},
constructor: function (config) {
this.initConfig(config);
}
});
Ext.create('Ext.panel.Panel',{
title: 'Define global variable in singletone class',
bodyPadding: 15,
items: [{
xtype: 'button',
text: 'Set value userId',
margin: '0 15',
handler: function () {
//we set value using setter of singleton.
Ext.Msg.prompt('New value of userId', 'Please enter userId value', function (btn, text) {
if (btn == 'ok') {
AppConstants.setUserId(text);
}
});
}
}, {
xtype: 'button',
text: 'Get value userId',
handler: function () {
//we get value using getter of singleton.
Ext.Msg.alert('userId value is ', AppConstants.getUserId());
}
}],
renderTo: Ext.getBody()
});
}
});