Undefined objects, trigger and self vs. this

For developers using the Construct 2 Javascript SDK

Post » Sun Dec 14, 2014 10:12 am

I am working on a plugin that should handle communication to and from a server. My code works in a regular html file but I am having problems getting it to work in a plugin. The errors I get are all related to some kind of ‘undefined’ objects. I have changed self to this and vice versa and moved things around but it will not work. I hope that some of you experienced plugin-developers or javascript developers can see the problem:

Code: Select all
   instanceProto.onCreate = function()
   {
      
       this.groupNo = "";

       // Declare a proxy to reference the hub.
       this.connection = $.hubConnection('http://myserver.com/');
       this.myHubProxy = this.connection.createHubProxy('myGameHub');

       this.myHubProxy.on('PrivateGameCreated', function (groupNoString) {
           self.groupNo = groupNoString;
           this.runtime.trigger(cr.plugins_.MyGame.prototype.cnds.PrivateGameCreated, self);          
       });
      ...
   };
   
   Cnds.prototype.PrivateGameCreated = function ()
   {
       return groupNo;
   };
   
   Acts.prototype.StartPrivateGame = function ()
   {
       this.connection.start().done(function ()
       {
            this.myHubProxy.invoke('createPrivateGame');
       });
   };
B
4
S
1
Posts: 8
Reputation: 366

Post » Sun Dec 14, 2014 10:33 am

Maybe add
Code: Select all
var self = this;

before use "self" object.
B
108
S
26
G
272
Posts: 4,471
Reputation: 152,277

Post » Sun Dec 14, 2014 11:14 am

I have tried to add “var self = this” in top of onCreate. The result is “cannot read property ‘invoke’ of undefined" (the same result as without "var self = this"). I get the error in this line:
Code: Select all
this.myHubProxy.invoke('createPrivateGame');
B
4
S
1
Posts: 8
Reputation: 366

Post » Mon Jan 05, 2015 1:18 pm

Google for some articles about JS "closures" and referencing vars outside of a "callback" :)
B
13
S
4
Posts: 280
Reputation: 1,578


Return to Javascript SDK

Who is online

Users browsing this forum: No registered users and 0 guests