0

I have a JS object that in pseudo code is doing this:

function myObj {
  // in constructor 
  ... initialise vars
  ... call $.Ajax to fetch view from server

    function AjaxCallBack() {
       // load the DOM with the HTML result
       $('#dialog').html(ajax.result);
       // try to register a change handler
       $("#dialog :input").change(this.formChangeEvent);
    }

    this.formChangeEvent = function(){
        ... do stuff
    }
}

The problem is that in the AjaxCallBack, 'this' is not myObj object, but rather the 'window' object and can't resolve the function

The only way I've been able to get around this problem is to have the receiver of the object call back into a separate function of myObj and register the event

objInstance = new myObj();
objInstance.registerEventHandler();

I've tried a few other things, but I'm obviously missing something basic.

BeNdErR
  • 17,471
  • 21
  • 72
  • 103
300baud
  • 540
  • 4
  • 17
  • Why are you posting pseudo code (including syntax errors) when you got a problem with an actual script? – GolezTrol Mar 28 '14 at 08:05
  • Could you post some info about how you call ajaxCallback since that's where the magic is :) – fiskeben Mar 28 '14 at 08:06
  • Post all the Things in your script – Sudharsan S Mar 28 '14 at 08:07
  • Lesson 1 - use google more effectively Lesson 2 - I should not have prefixed the function definition formChangeEvent with 'this'. That syntax enables the function to be publically accessed. By removing 'this' from the declaration, I am able to make the function private and it resolves without the need to use this or that. – 300baud Mar 29 '14 at 02:21

2 Answers2

1

If I understand your question then you can hold this to any variable like var thisObj=$(this) . Now you can use thisObj.formChangeEvent. Hope this will help.

Ashwani Panwar
  • 3,819
  • 3
  • 46
  • 66
0

Try this:

function myObj {
  // in constructor 
  ... initialise vars
  ... call $.Ajax to fetch view from server

    var oThis = this; // oThis is object this which points to myObj
    function AjaxCallBack() {
       // load the DOM with the HTML result
       $('#dialog').html(ajax.result);
       // try to register a change handler
       $("#dialog :input").change(oThis.formChangeEvent);
    }

    this.formChangeEvent = function(){
        ... do stuff
    }
}

It will do the trick.

Mohit Pandey
  • 3,679
  • 7
  • 26
  • 38