It appears you have not yet registered with DEVPPL. To register please click here... (it's fast, easy and free!)

Forum

Log In Sponsors
Board index Programming JavaScript Forum

self = this ... or how I learned to continue worrying but lo

self = this ... or how I learned to continue worrying but lo

Postby epimeth on Thu May 29, 2008 3:33 pm

so here's a *greatly simplified* snippet:
it uses the YUI event handler functions... if you don't know them then suffice it to say that:

YAHOO.util.Event.on ( el , sType , fn , obj , override )
Appends an event handler

Parameters:
el <String|HTMLElement|Array|NodeList> An id, an element reference, or a collection of ids and/or elements to assign the listener to.
sType <String> The type of event to append
fn <Function> The method the event invokes
obj <Object> An arbitrary object that will be passed as a parameter to the handler
override <Boolean|object> If true, the obj passed in becomes the execution scope of the listener. If an object, this object becomes the execution scope.

Code: Select all
function TopLevel() {
  function MyProblematicClass() {
    // here is why it is problematic:
    var self = null;

    var myObjectHandler = function(action, args) {
      var myProblematicFunction() {
        var myDiv = document.createElement('div');

        // here is where I use 'self' because 'this' did not work
        YAHOO.util.Event.on(myDiv, 'click', function() {
          this.someFunction();
        }, null, self);

      return myDiv;
      }

      switch(action) {
        case 'myAction':
          //here I define 'self' to be 'this'
          self = this;

          // here (the same scope as above!), 'this' *does* work
          this.someOtherFunction(myProblematicFunction());
          break;
        default:
      }
    }

    return new objectThatDefines_someFunction_and_someOtherFunction({
      objectHandler: myObjectHandler
    });
  }

  var myObj = new MyProblematicClass();
  myObj.callToThingWhichFiresTheHandler();
}


the call to myObj.callToThingWhichFiresTheHandler() doesn't actually occur where I placed it, but I think this is enough to post my question.

I can only assume that my problem lies in the fact that I instead of keeping to standard closure procedure I decided to return a reference to some newly created object. However, the code *does* work, so I really don't understand what the problem is.

If you want to get into slightly deeper specifics, the objectThatDefines_someFunction_and_someOtherFunction
is actually the ycarousel component found at http://www.billwscott.com/carousel/
Reply With Quote
epimeth
 
Posts: 0
Joined: Thu May 29, 2008 2:59 pm

Who is online

Users browsing this forum: No registered users and 5 guests