This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 9 years ago.
I've got something like the following:
MyShape = function() {
var _container = {
width: 100,
height: 100
}
this.draw() {
//do stuff...
}
$('#slider-1').bind('change', function(event, ui) {
_container.width = $('#slider-1').val();
this.draw();
});
};
I'm using the jquery slider to dynamically change the width of my shape, then I call .draw() to redraw the shape. I keep getting this error though:
Uncaught TypeError: Object # has no method 'draw'
I'm fairly sure it's because I need to pass the context "this" into the change function, but I can't seem to figure out how to do that.
This is caused because JavaScript's this is dynamic.
You can use Function.prototype.bind like so:
$('#slider-1').on('change', function(event, ui) {
_container.width = $('slider-1').val();
this.draw();
}.bind(this) /* use the same this value */);
Or you can use a closure variable
var that = this;
$('#slider-1').on('change', function(event, ui) {
_container.width = $('slider-1').val();
that.draw();
});
Related
This question already has answers here:
"this" keyword in event methods when using JavaScript prototype object
(4 answers)
How to access the correct `this` inside a callback
(13 answers)
Closed 2 years ago.
If a function inside an event listener is called, say for instance, window.load, are all other functions inside said function expected to be ran on load as well? I have an issue with a function being called on window load and that function calling another function. At the last step I want to add an event listener to watch for form submission. However the listener function has no access to the the variables called from the original load listener function.
var Handler = {
ajaxURL: null,
domIDs : null,
httpRequest : null,
init: function(config) {
this.httpRequest = {};
this.initConfig(config);
this.setLoadHandler();
},
initialize: function() {
this.initializeDocumentNodes();
},
setLoadHandler: function(){
var self = this;
this.addEvent(window,'load', function() {
self.initialize();
});
},
initializeDocumentNodes: function() {
this.dom = {};
for(var key in this.domIDs) {
this.dom[key] = document.getElementById(this.domIDs[key]);
}
this.dom['loginForm'].addEventListener("submit", function(ev) {
ev.preventDefault();
console.log(this.dom['userNameLoginInput']);
console.log(this.dom['passwordLoginInput']);
});
},
this.dom is undefined inside the form submit listener.
this.dom['loginForm'].addEventListener("submit", function(ev) {
ev.preventDefault();
console.log(this.dom['userNameLoginInput']);
console.log(this.dom['passwordLoginInput']);
});
Could someone please help me to understand this? Thank you so much.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 3 years ago.
How do I get this into a callback?
Started out with this, worked.
$('#grid').w2grid({
name : 'grid',
// Lost of setup
onMenuClick: function(event) {
$.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
// do some work
});
this.reload();
},
});
Then to only call reload if the request worked.
$('#grid').w2grid({
name : 'grid',
// Lost of setup
onMenuClick: function(event) {
$.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
// do some work
this.reload();
});
},
});
Of course "this" is no longer references the object I want to access.
Or how would I gain access the parent object?
You may just bind your this inside the callback.
Note: Beware of any side-effects. Apparently you don't seem to need the new this inside the callback.
Try:
$('#grid').w2grid({
name: 'grid',
onMenuClick: function(event) {
$.getJSON('?json=json&action=E&id=' + event['recid'], (function(data) {
this.reload();
}).bind(this));
}
});
When arrow-functions are available, I'd suggest to use them rather than binding this.
You can do it like this:
let parent = this;
$.getJSON('?json=json&action=E&id=' + event['recid'], function(data) {
// do some work
parent.reload();
});
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
here is my code, Now some people may say why not just include the one line code in that function block but i don't want to, how do i achieve that. How can i call this.click method on "click" event of the button
var i = 0;
function el() {
this.type = "button",
this.el = false,
this.click = function () {
this.setHtml(i++);
},
this.setHtml = function (t) {
this.el.innerHTML = t;
}
fragment = document.createDocumentFragment(),
element = fragment.appendChild(document.createElement(this.type));
element.setAttribute("data-el", this.type);
element.innerHTML = "Default Button";
this.el = element;
attachEvent("click", this);
}
// this should be a seperate function ....
function attachEvent(ev, me){
//me doesn't work, but i want it to call the click method
me.el.addEventListener("click", me.click, false);//....
}
div = new el();
document.getElementById('areaA').appendChild(div.el);
Change this:
me.el.addEventListener("click", me.click, false);//....
to this:
me.el.addEventListener("click", me.click.bind(me), false);//....
When you pass only me.click, you are just passing a reference to the click function and the binding to me is lost. .bind() will create a self-binding stub function that will give you the right this value when the event handler is called.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
i have problem that I can't understand:
var Copyright =
{
onLoad: function () {
this.initCopyrightMoving();
},
initCopyrightMoving: function () {
$(".sidebar_toggle").click(function () {
var copyright = document.getElementById("copyright-text");
if (copyright.className == "copyright-menu-open") {
this.decrease(280, 80, 10, copyright);
}
else
copyright.className = "copyright-menu-open"
});
},
decrease: function (actual_val, stop_val, step, copyright) {
setTimeout(function () {
if (actual_val == stop_val) {
copyright.className = "copyright-menu-closed";
}
actual_val = actual_val - step;
copyright.style.paddingLeft = parseInt(actual_val) + "px";
this.decrease(actual_val, stop_val, step, copyright);
}, 10);
}
};
and when I call initCopyrightMoving in line this.decrease(280, 80, 10, copyright);, I get this error:
copyright.js:14 Uncaught TypeError: this.decrease is not a function
at HTMLAnchorElement.<anonymous> (copyright.js:14)
at HTMLAnchorElement.dispatch (jquery-1.11.2.min.js:3)
at HTMLAnchorElement.r.handle (jquery-1.11.2.min.js:3)
can sm tell me what I did wrong? And also because I can't run next part of script can you tell me if decrease function is written good, I mean will it run properly.
this here is element $(".sidebar_toggle") you clicked.
Try defining var self = this; before jQuery handler and call self.decrease inside handler
this.decrease inside setTimeout will also not work for similar reason. Fix is the same
This is because this (context) changes when it's inside the click callback. One way you can stop the error is by preserving a copy of this and using that inside the callback.
initCopyrightMoving: function() {
var _this = this; // some developers use `self`
$(".sidebar_toggle").click(function() {
var copyright = document.getElementById("copyright-text");
if (copyright.className == "copyright-menu-open") {
_this.decrease(280, 80, 10, copyright);
} else {
copyright.className = "copyright-menu-open"
}
});
},
Here's a useful article on scope and context in JavaScript.
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 7 years ago.
I'll explain my issue using an example:
I have an object which is called 'ExampleObj' which returns 3 property 'init', 'age', 'weight' and I need to access from age to weight but for some reason i can't do that. Could you explain me why and how can I achieve the correct result?
EDIT: this is the current code, self.tabAnimation() is working on dom ready but... is not working on "click", even if I use (); check the **** in the code, is the line which triggers me error.
return {
init: function() {
var self = this;
tabs.init();
self.tabAnimation();
tabToggler.on('click', self.tabAnimation );
},
tabAnimation: function() {
var self = this;
var activeTabBars = function() {
console.log('lol');
tabItem.find(bars).each(function() {
var me = this;
****self.animateBars(me,1000)****
});
}
animateOnVisible.init(tabItem, activeTabBars);
},
animateBars : function(el, duration) {
var percentage = $(el).data('value') + "%";
$(el).animate({
'width': percentage
}, duration);
}
}
}
Thank you very much
Davide
You have to use this:
age: function() {
console.log('some random log');
var me = this;
me.weight;
me.weight(something);
},
You don't have to assign this to another variable, but it doesn't hurt anything if you do.
Note that in your "init" function,
self.age;
by itself will do nothing. To call the function, you have to write it
self.age();