Forum

[Solved] OO programming and B4W, passing "this" to a manifold callback function

31 December 2015 02:22
Hi,

I don't know if it is the good way, but I am trying to encapsulate some B4W code inside a JS object that I am going to instantiate later.

This object has some properties reflecting its state and some B4W properties and API functions to get a related blender object and bind some sensors to it.

function ModelOBJ() {
    // some props
    this.prop1 = true;
    this.prop2 = 0 ;
    ...   

    // some classic JS methods
    this.func = function(){
    ...
    }

   // some B4W code
   this.b4w_obj = m_scs.get_object_by_name('a_blender_obj');
   this.b4w_selector = m_ctl.create_selection_sensor(this.b4w_obj)

   this.b4w_obj_cb = function (obj, id, pulse){
       console.log(this.prop1);
   }

   m_ctl.create_sensor_manifold(this.b4w_obj, "OK", m_ctl.CT_SHOT,[this.b4w_selector], function(s){return s[0]}, this.b4w_obj_cb);

}

var object1 = new ModelOBJ();


Unfortunately, in the callback function this.prop1 cannot be accessed, and the result is undefined if you click on the object in the 3D scene. Is there a workaround to get the context of "this" instance so that we can r/w the properties of the instance and use its methods in the callback function ?

03 January 2016 05:51
Well, after some substantial searching on the net, the answer was relatively simple. At least, it works rather well right now for my project. I don't know if there are better ways to do that and hope it won't lead to any potential problems, but adding "bind(this)" to the callback function did the trick.

this.b4w_obj_cb = function (obj, id, pulse){
       console.log(this.prop1);
   }.bind(this);


(end of noob alert)
03 January 2016 20:24
Hi, glad you could find the solution. Sorry for little activity on the forums, we are enjoying very long holidays here in Russia (until 11 Jan).
The Founder | Twitter | Facebook | Linkedin
 
Please register or log in to leave a reply.