Javascript scope issues when binding - javascript

I know there are sooo many similar questions on stack regarding this issue, but for the life of me I cannot understand what the problem is in my code.
Trying to level up in javascript so any advise would be helpful. I have created an object to manage slider functions.
var gMapSlider = {
mapSlideShow: false,
// why doesnt current place update when passed in
newMarker: null,
oldMarker: null,
mapSlideIn: function() {
this.contentSlide
$('#placeDetails').animate({right: '0'});
this.mapSlideShow = true;
},
mapSlideOut: function(func) {
if (typeof(func) != "function") func = function() {};
$('#placeDetails').animate({right: '-320px'}, null, null, func());
this.mapSlideShow = false;
},
mapSlideToggle: function() {
(this.mapSlideShow) ? this.mapSlideOut() : this.mapSlideIn();
},
contentSlide: function() {
if (this.newMarker) $('h1', '#placeDetails').text(this.newMarker.title);
},
mapSlide: function(marker) {
this.newMarker = marker;
if (this.oldMarker === this.newMarker) { //same marker showing
this.mapSlideToggle();
}
else if (this.oldMarker !== this.newMarker && !this.mapSlideShow) { //diff marker showing
this.contentSlide(marker);
this.mapSlideIn();
}
else if (this.oldMarker !== this.newMarker && this.mapSlideShow) {
var self = this;
console.log(self) //returns this object
this.mapSlideOut(function() {
console.log(self); // returns this object
self.contentSlide(this.newMarker);
self.mapSlideIn;
}).bind(self); // cannot read property 'bind' of undefined
}
this.oldMarker = this.newMarker;
}
}
A couple of questions
1) The problem is with my gMapSlider.mapSlide function. If I call the mapSlide function and the last else if statement applies I get a cannot read property of bind error. I have Google'd but found nothing of any real relevance. Can anyone help with what I am doing wrong here.
2) Is this the best way of managing functions within a namespace. Most code samples I see use functions in the global namespace so wanted a bit of clarification if it is advised to create objects like this in Javascript?
EDIT #torazaburo Thanks, feel like a proper Newbie, that was the issue. Put it as an answer and I will put as solved. Any advice on code architecture?

this.mapSlideOut(function() {
console.log(self); // returns this object
self.contentSlide(this.newMarker);
this.mapSlideIn;
}).bind(self);
bind() should be called on a function object but you'r calling it on the result of a function call
use this:
this.mapSlideOut.bind(self,function() {
console.log(this); // returns this object
this.contentSlide(this.newMarker);
this.mapSlideIn;
});
also the above call will return you a reference to the function with this bound to self

Related

Javascript/jQuery Event Handler Scope inside object using keyword this

I've been trying for days to figure this out. I have read many questions on SO as well as googled it many different ways and read/attempted everything I found. Nothing I have found so far has worked for me and I have rewritten my code a million times it seems trying out different methods for doing this.
I feel like there is some super obvious thing I am missing here, and maybe just need a push in the right direction. If I'm going about this completely wrong and need to restructure everything, I can do that too.
Basically what I am working with is a front end "controller" for lack of a better word, that initializes some variables, sets up some event listeners and responds to user actions.
I don't care if I use jQuery or pure JavaScript, I just want it to work, even if I have to re-write the whole thing. My goal is speed and performance under heavy load. Another option I was considering was node.js but I have limited experience with that, so was hoping to figure it out with jQuery.
When the page loads, I do not get an error, but when I click one of the items that I have set an event listener on, I get the error... TypeError: Cannot Read Property 'apply' of undefined. And it refers to the corresponding line that starts with var scope = this ? function(e)...
The purpose of that line is to have the this keyword refer to the controller object so I can call object methods from within the event handler method. Though it seems it might not be working as I intended.
I tried to just use .on to set up the click and change handlers, but I was having problems with scope there as well. Any help, again, is much appreciated.
(function ($) {
$(function () { //document ready
function Controller(authId, authKey) {
this.user.id = authId;
this.user.key = authKey;
this.init();
};
Controller.prototype = {
eventChange: [ "amt", "multi" ],
eventClick: [ "double", "half", "high", "low" ],
event: { refresh: ['amt', 'multi'], update: ['double', 'half'], process: ['high', 'low'] },
user: { id: '', key: '', name: '', balance: '' },
init: function () {
this.initEvents();
},
initEventz: function() {
for (var i = 0; i < this.eventChange.length; i += 1) {
var ele = document.getElementById(this.eventChange[i]);
var scope = this ? function(e) { this.handleEvent.apply(this, ["change"]); } : this.handleEvent;
if(document.addEventListener) {
ele.addEventListener("change", scope, false);
} else if(document.attachEvent) {
ele.attachEvent("onchange", scope);
}
}
for (var i = 0; i < this.eventClick.length; i += 1) {
var ele = document.getElementById(this.eventClick[i]);
var scope = this ? function(e) { this.handleEvent.apply(this, ["click"]); } : this.handleEvent;
if(document.addEventListener) {
ele.addEventListener("click", scope, false);
} else if(document.attachEvent) {
ele.attachEvent("onclick", scope);
}
}
},
handleEvent: function (e) {
var eventId = e.target.id;
for (var event in this) {
if (this.hasOwnProperty(event)) {
console.log(event);
}
}
}
};
var Controller = new Controller($("#auth").val(), $("#key").val());
}); //end document ready
})(jQuery);
You are losing the reference to this.
You can solve that with this code:
var scope = this ? function(e) { this.handleEvent.apply(this, ["click"]); }.bind(this) : this.handleEvent;
but if you want that the handler have access to the element within his scope with the reference of this you should write this:
var scope = this ? function(e) { this.handleEvent.apply(ele, ["click"]); }.bind(this) : this.handleEvent;
or this
var that = this;
var scope = this ? function(e) { that.handleEvent.apply(ele, ["click"]); } : this.handleEvent;
I have seen other mistake. Because if this is undefined then scope is going to be this.handleEvent but this is going to raise an error because undefined can't have the handleEvent property.

Getting correct scope in functions (not using that = this)

I am trying to fix a function I have here to be able to use it without using a that = this (or self = this as some like to use). It is a scoping issue but I am not sure how to get around it, and I would like to get in the habit of not using a that = this . So the functions are all in a return (angular factory) and I am having trouble referencing another function . Let me show you what I mean :
return {
loadStates: function() {
var that = this;
//chgeck if is loaded module, then change and fire callback
var currentModules = moduleHolder.getModules();
if (currentModules[name]) {
//works here
this.prepState();
} else {
//module cannot be found check for 5 seconds
$log.warn("Requesting " + name + "...");
var timeToCheck = true;
setTimeout(function() {
timeToCheck = false;
}, 5000);
var check = {
init: function() {
check.checkAgain();
},
checkAgain: function() {
if (timeToCheck) {
if (currentModules[name]) {
//but not here
that.prepState();
} else {
//still doesn't exists
setTimeout(check.checkAgain, 200);
}
} else {
//doesn't exist after 5 seconds
$log.error("Requested module (" + name + ") could not be found at this time.");
}
}
};
check.init();
}
},
prepState: function() {
}
}
So in the top if it finds the currentModule[name] I can use a this.prepState() and it works fine. However inside the timing functions I cannot use the this anything because it is inside a different scope so I have temporarily gotten around this by setting a that = this up top, however I would like see if I could not use this method. How does one get around this without using the that= this? Thanks!
It is a scoping issue...
No, it isn't. this and scope have essentially nothing to do with each other. (For now; ES6's arrow functions will change that.) It's an issue of how the functions are called.
If you pass a function reference to something that will call it later, unless the thing you're passing it to has a way you can use to tell it what to use for this when calling it, your function will get called with this not referring to what you want it to refer to.
You can get a new function reference that will call your original function with the correct this by using Function#bind:
var usesCorrectThis = originalFunction.bind(valueForThis);
So for example, suppose I have:
var check = {
name: "Fred",
sayHello: function() {
console.log("Hi, I'm " + this.name);
}
};
If I do:
check.sayHello();
All is good: Calling the function as part of an expression retrieving it from a property tells the JavaScript engine to use the object as this during the call.
However, if I do:
setTimeout(check.sayHello, 0);
...that doesn't work right, because when setTimeout calls the function, it doesn't use the right value for this.
So I can use Function#bind to address that:
setTimeout(check.sayHello.bind(check), 0);
More (on my blog):
Mythical methods
You must remember this
there are different ways you can do that.
One way is to use bind function.you can use
var checkInitBindFn = check.init.bind(this);
checkInitBindFn();
Secondly you can use call and apply also.
check.init.call(this);
check.init.apply(this);
Like this you can use this instead of that.
Check the complete api doc online...
It's not a scoping issue. If you want to avoid self = this you can always reference functions by objects. Makes cleaner code and since factories in angular are singletons you're not wasting memory.
angular.module('myApp').factory('myFactory', function ($timeout) {
var myFactory = {
loadState: function () {
$timeout(function () {
myFactory.check();
}, 500);
},
check: function () {
},
};
return myFactory;
});

need help understanding closures usage in this code

Here is a simplified snippet from some code I wrote for managing tablet gestures on canvas elements
first a function that accepts an element and a dictionary of callbacks and register the events plus adding other features like 'hold' gestures:
function registerStageGestures(stage, callbacks, recieverArg) {
stage.inhold = false;
stage.timer = null;
var touchduration = 1000;
var reciever = recieverArg || window;
stage.onLongTouch = function(e) {
if (stage.timer) clearTimeout(stage.timer);
stage.inhold = true;
if (callbacks.touchholdstart) callbacks.touchholdstart.call(reciever, e);
};
stage.getContent().addEventListener('touchstart', function(e) {
e.preventDefault();
calcTouchEventData(e);
stage.timer = setTimeout(function() {
stage.onLongTouch(e);
}, touchduration);
if (callbacks.touchstart) callbacks.touchholdstart.call(reciever, e);
});
stage.getContent().addEventListener('touchmove', function(e) {
e.preventDefault();
if (stage.timer) clearTimeout(stage.timer);
if (stage.inhold) {
if (callbacks.touchholdmove) callbacks.touchholdmove.call(reciever, e);
} else {
if (callbacks.touchmove) callbacks.touchmove.call(reciever, e);
}
});
stage.getContent().addEventListener('touchend', function(e) {
e.preventDefault();
if (stage.timer) clearTimeout(stage.timer);
if (stage.inhold) {
if (callbacks.touchholdend) callbacks.touchholdend.call(reciever, e);
} else {
if (callbacks.touchend) callbacks.touchend.call(reciever, e);
}
stage.inhold = false;
});
}
later I call registerStageGestures on a few elements (represented by 'View' objects) in the same page. Something like:
function View() {
var self=this;
..
function InitView() {
...
registerStageGestures(kineticStage, {
touchstart: function(e) {
// do something
},
touchmove: function(e) {
// do something
},
touchendunction(e) {
// do something
},
touchholdstart: function(e) {
// do something
},
touchholdmove: function(e) {
// do something
},
touchholdend: function(e) {
// do something
},
}, self);
Everything works fine, however I'm left wondering about two things in the implementation of registerStageGestures:
First, is it necessary to make inhold, timer and onLongTouch members of the stage ? or will closures make everything works well if they are local vars in registerStageGestures ?
Second, is it necessary to call the callbacks with '.call(receiver,' syntax ? I'm doing this to make sure the callback code will run in the context of the View but I'm not sure if it's needed ?
any input is much appreciated
Thanks!
First, is it necessary to make inhold, timer and onLongTouch members
of the stage ? or will closures make everything works well if they are
local vars in registerStageGestures ?
As far as registerStageGestures() is concerned, var inhold, var timer and function onLongTouch(e) {...}. would suffice. The mechanism by which an inner function has automatic access to its outer function's members is known as "closure". You would only need to set stage.inhold, stage.timer and stage.onLongTouch if some other piece of code needs access to these settings as properties of stage.
Second, is it necessary to call the callbacks with '.call(receiver,'
syntax ? I'm doing this to make sure the callback code will run in the
context of the View but I'm not sure if it's needed ?
Possibly, depending on how those callbacks are written. .call() and .apply() are sometimes used when calling functions that use this internally. In both cases, the first parameter passed defines the object to be interpreted as this. Thus, javascript gives you the means of defining general purpose methods with no a priori assumption about the object to which those methods will apply when called. Similarly, you can call a method of an object in such a way that it acts on another object.
EDIT:
For completeness, please note that even in the absence of this in a function, .apply() can be very useful as it allows multiple parameters to be specified as elements of a single array, eg the ubiquitous jQuery.when.apply(null, arrayOfPromises)...
There are some simple answers, here.
First, closure:
Closure basically says that whatever is defined inside of a function, has access to the rest of that function's contents.
And all of those contents are guaranteed to stay alive (out of the trash), until there are no more objects left, which ere created inside.
A simple test:
var testClosure = function () {
var name = "Bob",
recallName = function () { return name; };
return { getName : recallName };
};
var test = testClosure();
console.log(test.getName()); // Bob
So anything that was created inside can be accessed by any function which was also created inside (or created inside of a function created in a function[, ...], inside).
var closure_2x = function () {
var name = "Bob",
innerScope = function () {
console.log(name);
return function () {
console.log("Still " + name);
}
};
return innerScope;
};
var inner_func = closure_2x();
var even_deeper = inner_func(); // "Bob"
even_deeper(); // "Still Bob"
This applies not only to variables/objects/functions created inside, but also to function arguments passed inside.
The arguments have no access to the inner-workings(unless passed to methods/callbacks), but the inner-workings will remember the arguments.
So as long as your functions are being created in the same scope as your values (or a child-scope), there's access.
.call is trickier.
You know what it does (replaces this inside of the function with the object you pass it)...
...but why and when, in this case are harder.
var Person = function (name, age) {
this.age = age;
this.getAge = function () {
return this.age;
};
};
var bob = new Person("Bob", 32);
This looks pretty normal.
Honestly, this could look a lot like Java or C# with a couple of tweaks.
bob.getAge(); // 32
Works like Java or C#, too.
doSomething.then(bob.getAge);
? Buh ?
We've now passed Bob's method into a function, as a function, all by itself.
var doug = { age : 28 };
doug.getAge = bob.getAge;
Now we've given doug a reference to directly use bobs methid -- not a copy, but a pointer to the actual method.
doug.getAge(); // 28
Well, that's odd.
What about what came out of passing it in as a callback?
var test = bob.getAge;
test(); // undefined
The reason for this, is, as you said, about context...
But the specific reason is because this inside of a function in JS isn't pre-compiled, or stored...
this is worked out on the fly, every time the function is called.
If you call
obj.method();
this === obj;
If you call
a.b.c.d();
this === a.b.c;
If you call
var test = bob.getAge;
test();
...?
this is equal to window.
In "strict mode" this doesn't happen (you get errors really quickly).
test.call(bob); //32
Balance restored!
Mostly...
There are still a few catches.
var outerScope = function () {
console.log(this.age);
var inner = function () {
console.log("Still " + this.age);
};
inner();
};
outerScope.call(bob);
// "32"
// "Still undefined"
This makes sense, when you think about it...
We know that if a function figures out this at the moment it's called -- scope has nothing to do with it...
...and we didn't add inner to an object...
this.inner = inner;
this.inner();
would have worked just fine (but now you just messed with an external object)...
So inner saw this as window.
The solution would either be to use .call, or .apply, or to use function-scoping and/or closure
var person = this,
inner = function () { console.log(person.age); };
The rabbit hole goes deeper, but my phone is dying...

Question regarding "this" inside anonymous function of prototype.js .each method

I've been searching for hours for a solution to this problem. I'm creating a table using prototype.js 1.6.0.1 and am having trouble with the this object in context with the .each function. here is a snippit.
var Table = Class.create({
initialize : function(id) {
this.elmnt = $(id);
this.rows = [];
},
initRows : function() {
$A(this._elmnt.tBodies).each(function(body) {
$A(body.rows).each(function(row) {
//right here is where i would like to call
// this.rows.push(row);
console.log(this); // prints DOMWindow
});
});
}
});
As you can see inside the second .each function this resolves to DOMWindow. I would like to be able to call this.rows.push(row) but I can't as "this" isn't resolving as expected.
Any help would be appreciated. I know i could do the standard (i=0; i < length; i++) loop but I was trying to make this a little cleaner. Thanks for any guidance you can offer.
The easiest way to work around this is to save this at the start of initRows and refer to in within the each functions
initRows : function() {
var self = this;
$A(this._elmnt.tBodies).each(function(body) {
$A(body.rows).each(function(row) {
//right here is where i would like to call
self.rows.push(row);
console.log(self); // prints DOMWindow
});
});
}
The problem you're running into is that this can be manipulated by the caller of the function. It's very common in callbacks to set this to an element which is relevant to the call back. In the case of each it's set to the element for the current iteration of the value.
The self trick works because it saves the this as it's bound in the function initRows and then uses that saved value in the iteration.
initRows : function() {
$A(this._elmnt.tBodies).each(function(body) {
$A(body.rows).each((function(e, row) {
e.rows.push(row);
console.log(e);
}).bindAsEventListener(this, row));
});
}

Define a function that will be implemented by the user

I have the following example code
var object = {
userDefinedFunction : function(){
//no implementation, this will be defined by the user
}
}
What i want to achieve is the user giving his own implementation of it:
object.userDefinedFunction = function(){
alert("just testing");
}
I tested this and works as i expected, what i want to know is:
is this the javascript way of solving this kind of problem?
let's say that it's mandatory that userDefinedFunction is implemented, how do i make sure of this? I could rely on something like the following, checking for implemented, but i'm learning javascript so i want to know how to leverage the language:
userDefinedFunction : function(){
implemented = false;
}
Thank you.
I don't know if this is the way to go, but if your object has to be initialized somehow by the user, you can test in this function, whether userDefinedFunction is defined and throw an exception if not.
One idea that feels to be a cleaner implementation, is to let the user provide some kind of configuration object that defines the functions, something like:
yourObject.initialize({
userDefinedFunction: function() {}
});
You could throw an error in the default implementation:
var object = {
userDefinedFunction : function(){
throw "userDefinedFunction must be implemented";
}
}
or show an alert box, depending on your application.
var object = {
userDefinedFunction : undefined,
anotoherDefinedFunc : undefined,
/* ... */
hasUserImplementedInterfaces : function() {
if (typeof object.userDefinedFunction !== 'function') return false;
if (typeof object.anotoherDefinedFunc !== 'function') return false;
/* ... */
return true;
}
};
console.log(object.hasUserImplementedInterfaces());
hasUserImplementedInterfaces() function checks for user function implementations so you can execute as first check using that object.

Categories

Resources