I’ll start with an example snippet:
self.addwidget({
box: ns.box({
text: 'Foobar',
fromTop: ~~(Math.random()*window.innerHeight),
fromLeft: ~~(Math.random()*window.innerWidth),
toTop: 240,
toLeft: 40,
css: 'foobar',
easing: 'easeOutCirc',
duration: 2000,
events: {
mousedown: function(e){
e.target.position = {x: e.pageX, y: e.pageY};
},
mouseup: function(e){
// "this" should reference be "box"
}
}
}),
delay: 3000
});
Short description:
ns.box() takes an object as argument and creates a new jQuery object. It uses jQuery.extend() to merge the events property object with the jQuery constructor $('<elem/>', {});
After that, ns.box() returns a new object which contains some methods.
—
What I want to archieve is to have access to those propertys / methods within the event handlers. Of course I cannot access box.somemethod at this point because I cannot reference the outer box property at this point. So I tried to change the scope from the event handlers with jQuery.proxy(), to this, but with no success.
this.somemethod is unreferenced even when proxied.
I also tried to proxy all objects top->down, no success either.
Is it even possible in a construct like this one, to access the propertys from the returned object of ns.box(), within the event handlers ?
You can achieve this with a scoping function, like this:
By assigning the box to a var inside our scoping function, we create a symbol that the event handlers (which are closures) close over and thus have access to. We call the function immediately, having it return the object. References held by closures are enduring, and so…
I use this pattern all the time because I don’t like having anonymous functions (your event handlers are anonymous, for instance); more here. If I were doing the above, I’d make those named instead, like this:
Those functions now have names that can show up in call stacks and error messages, but they’re completely private, not cluttering up the global namespace.