JS bind the context of a function before passing - javascript

I'm trying to setup a function that stores a callback which can be fired later on an event, but I'm not getting the context to bind right. The setup is basically like this:
app.myObject = function(){
this.bindEvents();
};
app.myObject.prototype = {
bindEvents: function(){
var self = this;
this.library = new OutsideLibrary();
this.library.onMyEvent = function(data) {
OtherLibrary.processData(data, self.runCallback); // I'm not able to pass a context here...
}
},
sendToLibrary: function(message,callback) {
this.callback = callback;
this.library.send(message);
}
// ... and this doesn't work because it gets evaluated in the wrong context.
runCallback: function() {
if (this.callback) {
this.callback();
this.callback = null;
}
}
}
I hope the above code makes sense. The idea is, I'm trying to expose an API where I can call:
app.myObject.sendToLibrary("something", function() {...});
...and the callback function will run after the whole chain is complete.
The problem is, I can't pass the callback that is received in sendToLibrary directly through, because the callback need to be passed to another object when an event fires. Also since I'm having to store the currently passed callback, and the callback is optional, I need to unset it once it has fired, so I actually need to pass the runCallback function to run the callback once then unset it.
Anyway, the problem is that when runCallback eventually gets executed it is no longer in the correct context, so it doesn't work. My first idea for how to fix this was to change the runCallback function to include a context argument, so I could pass self.runCallback(self) -- but that executes immediately so it defeats the purpose.
Anyway, I'm sort of lost in the callback woods here, and would appreciate some help finding my way out :)
My question is: is there a way to wrap up a callback function and the correct context, without executing it now, so that when it eventually fires it does so from the correct context?
Thanks!

OtherLibrary.processData(data, function() {
self.runCallback();
)};
Then inside of runCallback this refers to an instance of app.myObject, if this is what you want.

Andrew, I think you might be trying a little too hard, here.
If all you're looking to do is bind context, you can do one of the following:
var working_method = context.method.bind(context);
// bind is IE9+, and does something similar to the below
// or, from whatever scope your context/method are available in, define this function
var working_method = function () { context.method(); };
If you require parameters, and you already know the footprint:
var working_method = function (a, b, c) { context.method(a, b, c); };
The solution for variable argument lengths (ie: a generalized "bind" method) is longer, but if you're defining stuff in line, what I've got here might be all you need.
Just make sure that you do not use this in your wrapping function (whether you save it to a var, or pass it directly into another function), because it will reference window.

Related

Recognising variables while assigning a function to a variable in javascript

In my jQuery scripts, when the user closes a menu with an animation, I have to call a function after the closing animation is finished. I want to assign this function dynamically by calling a function openStrip() with a parameter. My code looks like:
var FUNCTION_JUST_AFTER_MENU_CLOSE = function(){};
function openStrip(stripId){
FUNCTION_JUST_AFTER_MENU_CLOSE = function(){
createStrip(stripId);
});
}
if I call openStrip("aStripId"), I expect FUNCTION_JUST_AFTER_MENU_CLOSE to be:
// #1
function(){
createStrip("aStripId");
}
whereas my current code gives:
//#2
function(){
createStrip(stripId);
}
i.e, the parameter passed to the function openStrip() is lost while assigning the function() to the variable FUNCTION_JUST_AFTER_MENU_CLOSE.
How can I avoid this.
EDIT: I discovered that my code is actually working. The problem was elsewhere. I got confused because when I looked at Chrome's debugger, it was showing me the function definition as is (#2 in above). But when it actually went down executing that function later in the code, it did evaluate the values of the passed argument, and endedup executing #1.
Thanks for the answer though. I am marking it correct because that is perhaps a better way of assigning the function.
The best way is to return a function, from openStrip like this
function openStrip(stripId) {
return function() {
createStrip(stripId);
};
}
For example,
function openStrip(stripId) {
return function() {
console.log(stripId);
};
}
openStrip("aStripId")();
# aStripId
openStrip("bStripId")();
# bStripId
You can even assign the function objects returned to different variables and use them later on
var aStrip = openStrip("aStripId");
aStrip();
# aStripId
aStrip();
# aStripId

Getting function arguments within another function

I've heard that it's possible to do something like this
this[func].apply(this, Array.prototype.slice.call(arguments, 1));
But to have access to the arguments object I need to be inside that function.
So, if I am, for example, running a code in the function function1, is there a way to get the arguments of a different function function2?
The whole problem is that I want to add events to any given element. But this element might already have another event attached to it. so, if I have, for example, an 'onclick' event attached to an element, I would do the following:
var event = 'onclick';
if(typeof currentElement[event] === 'function'){
cf = currentElement[event];
f = function(){
cf();
func();
}
}else f = func;
currentElement[event] = f;
Now both functions, the new function and the previous function, are being called. The problem is that the arguments being passed to the previous function were lost with this method.
Does anyone know if it is possible to not lose the arguments when we call a function dynamically like in my example?
OBS: jQuery is not an option :/
Sounds like using addEventListener would work better for you. It lets you attach multiple listeners (functions) to a single element:
elem.addEventListener("click", function() {
console.log("click listener 1");
});
elem.addEventListener("click", function() {
console.log("click listener 2");
});
Note, according to MDN, addEventListener is supported in IE >= 9.
If you did want to continue down your current path, you could do:
f = function(){
cf.apply(this, arguments);
func.apply(this, arguments);
}
For you specific case, it's not necessary to figure out what arguments are passed to the function since you know what it is - the event object in all browsers except (older) IE where its nothing (undefined).
So the code can simply be:
var event = 'onclick';
if(typeof currentElement[event] === 'function'){
cf = currentElement[event];
f = function(e){
cf(e);
func(e);
}
} else f = func;
currentElement[event] = f;
If possible use addEventListner and attachEvent as fallback to play nicely with other scripts that may run on your page.
Additional discussion:
In general, it is never necessary to figure out what has been passed to the callback function because that doesn't even make sense. The programmer cannot determine what to pass to the callback, it's the event emitter that determines what gets passed. In this case its the event object but it's a general rule.
Say for example we have an API that queries our database and returns some data:
function my_api (query) {}; // returns an object where a callback may
// be attached to the oncomplete property
The API documentation mentions:
my_api() returns an API object.
API object - has one property - oncomplete where a callback may be attached to handle data returned from the api call. The callback will be called with one argument - the returned data or no argument (undefined) if an error occured.
OK. So we use it like this:
var db = my_api('get something');
db.oncomplete = function (data) {alert(data)};
Now, if we want to wrap that oncomplete event in another event handler, we don't need to know what data it accepts since it's the API object that determines what to pass to the function, not the function! So we simply:
var tmp = db.oncomplete;
db.oncomplete = function (x) {
new_callback(x);
tmp(x);
}
We get the x argument not from querying the previous callback but from the documentation.
somefunction.arguments //Use the arguments property to get arguments of another function

Call functions within event handler

I have written two functions in JavaScript code as follows
Manager = FormManager.extend({
First: function () {
var response = this.Second("Feature"); //I'm able to get the alert
//I have added a click event handler
$('#element').on('click', function(){
var newResponse = this.Second("Bug"); //The alert is not poping
});
}
Second: function (type) {
alert(type);
//Performs certain operation
}
});
Error: Uncaught TypeError: Object #<HTMLButtonElement> has no method 'Second'
I also tried without using this keyword like:
Second("Bug") // Error: There is no method
Whereas this a simplified format (in-order to show a simple example) on my program that I'm playing with. I'm struggling to find out the reason.
Can someone direct me to the right path?
You are using incorrect this. try this way. this inside the handler represents #element not the context of the function itself.
var self = this; //cache the context here
$('#element').on('click', function(){
var newResponse = self.Second("Bug"); //Access it with self
});
Also i think you are missing a comma after First function definision and before Second function.
Fiddle
The reason being the callback you give gets invoked from within the context of the element so your this context changes. this context refers to the context from where the callback was invoked. But there are other ways to get around this like using $.proxy while binding your callback with jquery, using EcmaScript5 Function.prototype.bind etc. But ideally you don't want to do that because most of the cases you would need the context of the element there inside the handler.
Every time you use the this context variable in a function you have to consider what its value is.
Specifically that value will be whatever value the caller specified, whether by using myObj.mymethod(...), or mymethod.call(myObj, ...), or mymethod.apply(myObj, [ ... ]).
When your anonymous function $('#element').on('click', ...) is invoked jQuery will set the context to the HTML DOM element - it's no longer referring to your object.
The simplest work around is to obtain a copy of this outside of the callback, and then refer to that copy inside the closure, i.e.:
var that = this;
$('#element').on('click', function() {
// use that instead of this, here
console.log(this); // #element
console.log(that); // your object
});
Another method is using Function.prototype.bind:
$('#element').on('click', (function() {
console.log(this); // your object
}).bind(this));
or with jQuery you can use $.proxy for the same effect, since .bind is an ES5 function.
I actually prefer the var that = this method, since it doesn't break the jQuery convention that this refers to the element associated with the event.

Expecting the right calling context (this) in the JavaScript object

Consider this:
window.onload = function () {
myObj.init();
};
var myObj = {
init: function () {
console.log("init: Let's call the callMe method...");
//callMe is not defined...
callMe();
//Works fine!
this.callMe();
},
callMe: function () {
console.log('callMe');
}
};
Since the init function gets called this way (myObj.init), I expect this to be myObj in the init function. And if that is the case, why the callMe function fails? How am I supposed to call the callMe function without using the this context in the init body? (Actually, it's too annoying to call the object methods using this over and over again through the functions. So what's the point of having a single object?)
I would like to know how can I fix this so that the callMe method gets called using the first invocation in the code above?
this is never implicit in JavaScript as it is in some other languages. Although there are ways to do it, like this using the with statement:
init: function () {
console.log("init: Let's call the callMe method...");
// Make `this` implicit (SEE BELOW, not recommended)
with (this) {
// Works
callMe();
}
},
...it's generally a bad idea. Douglas Crockford probably wrote one of the better descriptions of why it's a bad idea, which you can find here. Basically, using with makes it nearly impossible to tell what the code's going to do (and slows the code down, if you do anything else in that with statement that doesn't come from the this object).
This isn't the only way that JavaScript's this is not the same as it is in some other languages. In JavaScript, this is defined entirely by how a function is called, not where the function is defined. When you do this.callMe() (or the equivalent this["callMe"](), or of course foo.callMe(), etc.), two things happen: The function reference is retrieved from the property, and the function is called in a special way to set this to be the object that property came from. If you don't call a function through a property that way, the call doesn't set any particular this value and you get the default (which is the global object; window on browsers). It's the act of making the call that sets what this is. I've explored this in depth in a couple of articles on my blog, here and here.
This (no pun) can be made even clearer if you look at JavaScript's call and apply functions, which are available on all function objects. If I do this:
callMe.call({});
...it'll call the callMe function with a blank object ({}) as this.
So basically, just get used to typing this. :-) It's still useful to have properties and methods associated with an object, even without the syntactic convenience (and confusion!) of an implicit this.
You can also use the module pattern, which captures all private variables inside a closure, so you are free to use them without this, as they're in the same scope. You then pick and choose which methods/variables you want to make public:
var myObj = (function () {
var init = function () {
callMe(); // This now works
};
var callMe = function () {
...
};
// Now choose your public methods (they can even be renamed):
return {
init: init, // Same name
callMyName: callMe // Different name
};
}) ();
Now:
myObj.init(); // Works
myObj.callMyName(); // Works
myObj.callMe(); // Error

can you say this is a right example of Javascript Closure.. Where the places we need to consider avoiding the closures?

Problem & Reason
One of my team mate ended up in messy situtaion implementing function hooking in javascript. this is the actual code
function ActualMethod(){
this.doSomething = function() {
this.testMethod();
};
this.testMethod = function(){
alert("testMethod");
};
}
function ClosureTest(){
var objActual= new ActualMethod();
var closeHandler = objActual.doSomething;
closeHandler();
closeHandler.apply(objActual,arguments); //the fix i have added
this.ActualTest = function() {
alert("ActualTest");
};
}
In the above code, var closeHandler is created in the context of ClosureTest(), but it holds the handler of the ActualMethod.doSomething. Whenever calling the closeHandler() ended up in "object doesnt support this method" error.
This is because doSomething() function calls another method inside called this.testMethod();. Here this refers to the context of the caller not callee.so i assume the closeHandler is bound to the environment(ClosureTest) actually created.Even though it holds the handler to the another context, it just exposes the properties of its own context.
Solution
To avoid this i suggest to use apply to specify the conext in which it needs to execute.
closeHandler.apply(objActual,arguments);
Questions
is it perfect scenario for closures..??
What are the intersting places you have encountered closures in javascript..?
UPDATE
Yes its simple i can call the method directly. but the problem is, in a particular scenario I need to intercept the call to actuall method and run some code before that, finally execute the actual method..
say for an example, am using 3rd party aspx grid library, and all the mouseclick events are trapped by their controls. In particular group by mouse click i need to intercept the call to their ilbrary method and hook my mthod to execute instead and redirect the call to actual library method
hope this helps
Update: Because you probably left out some details in your code, it is difficult to adapt it into something workable without missing the point of your actual code. I do think I understand your underlying problem as you describe it. I hope the following helps.
Suppose the following simple example:
// Constructor function.
function Example() {
// Method:
this.method = function() {
alert("original method");
}
}
// You would use it like this:
var obj = new Example();
obj.method(); // Calls original method.
To intercept such a method call, you can do this:
function wrap(obj) {
var originalMethod = obj.method;
obj.method = function() {
alert("intercepted call");
originalMethod.apply(this, arguments);
}
return obj;
}
var obj = wrap(new Example());
obj.method(); // Calls wrapped method.
Unfortunately, because method() is defined in the constructor function, not on a prototype, you need to have an object instance to wrap the object.
Answer to original question: The doSomething() function is used as a method on objects created with ActualMethod(). You should use it as a method, not detach it and use it as a function in a different context. Why don't you just call the method directly?
function ClosureTest(){
var objActual = new ActualMethod();
// Call method directly, avoid messy apply() calls.
objActual.doSomething();
this.ActualTest = function() {
alert("ActualTest");
};
}
If you assign a method (a function on some object) to a local variable in Javascript and call it, the context will be different (the value of this changes). If you don't want it to happen, don't do it.
When I want to hook a function, I use the following Function method which is also a fine piece of Closure demonstration:
Function.prototype.wrap = function (wrapper) {
var __method = this;
return function() {
var __obj = this;
var args = [ __method.bind(__obj) ];
for(var i=0; i<arguments.length; i++) args.push(arguments[i]);
return wrapper.apply(__obj, args);
}
};
Then do something like:
ActualMethod = ActualMethod.wrap(function (proceed, option) {
// ... handle option
proceed(); // calls the wrapped function
});
proceed is bound to its initial object, so you can safely call it.

Categories