This could be a very basic Javascript I know but I just can’t get it..
Ext.regController('Chat', {
initSocketConnection: function() {
this.chatStore = new App.Store.Chat();
...
this.socket = io.connect(settings.get('server'), {port: 8080});
this.socket.on(
'message',
this.addMessageToChatStore
);
},
addMessageToChatStore: function(message) {
console.log(message);
console.log(this); << console shows the 'this' has become SocketNameSpace
this.chatStore.add(message); << this line error with "Undefined" chatStore
this.send(message);
},
Console print out shows that the "this" in the addMessageToChatStore function is "SocketNamespace"
How to I get rid of the error?
To generalize the problem. I think it’s better to describe it as function chain calling dilemma.
A class has some local var that’s instance of another class. When this var listens on certain events, it calls the parent’s class’s method. The problem is when this method is called, it’s under the context of the other class and hence the scope has changed and the access to the original parent’s class methods are denied.
In javascript, the
thisvariable is determined by the caller. You could use a self executing function to ensure you’re referencing the correct entity rather than usingthis:Update
Based on the full snippet, I’m not sure where the
renderfunction is defined, ifrenderis a global function thenself.viewChat = render({xtype : 'App.View.Chat'});will suffice, otherwise it may be defined onthis(thethisthat is defined for the call toindex) so the following may sufficeself.viewChat = this.render({xtype : 'App.View.Chat'});.If I were a betting man, I’d go for the latter, so the code would be (with commented out code removed):