Reputation: 735
I'm trying to get familiar with singleton in sencha, but my getters return me UNDEFINED everytime... Why? My alert should be displaying 'Bob' but it returns undefined.
here is my handler
handler: function(button, event) {
var user = Prototype.model.Profile;
alert(user._username);}
Here is my singleton
Ext.define('Prototype.model.Profile', {
extend: 'Ext.data.Model',
singleton: true,
config: {
fields: [
{
name: 'listEvent',
type: 'auto'
},
{
name: 'listBusiness',
type: 'auto'
},
{
name: 'listTravel',
type: 'auto'
},
{
defaultValue: {
username: 'bob'
},
name: 'username'
}
]
},
addTravel: function(newTravel) {
this._listTravel.push(newTravel);
},
getTravel: function(travelTitle) {
var travel;
for(var i=0; i<this._listTravel().getLength(); i++)
{
if(this._listTravel[i].getTitle()==travelTitle)
{
travel=this._listTravel[i];
break;
}
}
}
});
Upvotes: 0
Views: 913
Reputation: 735
The getters and setters work fine. It's the default value which is not working properly. Can't explain why if someone would know, I would accept their answer.
Upvotes: 0
Reputation: 2035
First, I think the config part for that should be:
config: {
fields: [
{
name: 'listEvent',
type: 'auto'
},
{
name: 'listBusiness',
type: 'auto'
},
{
name: 'listTravel',
type: 'auto'
},
{
defaultValue: 'bob', // Instead of extra 'username' here
name: 'username'
}
]
},
However, I don't think singletons are meant to be used that way (with Model class). Because singleton will always only create a single instance to your class while your Model objects usually should be independent.
In my opinion, you should only use singleton for util classes. Something that you want to call in any context. Like this:
Ext.define('myApp.utils.AppConfig', {
singleton: true,
// Default value declared like this, without the config object
defaultValue: 'something',
alternateClassName: 'AppConfig',
log: function(text) {
if (typeof console !== 'undefined') {
console.log(text);
}
}
});
Then call it like this in your controllers/views
AppConfig.log('Oh yes ' + AppConfig.defaultValue); // print 'Oh yes something'
Upvotes: 1