The problem is with object's variable:
this.timer
it's not "global", so when I click the stop button the value of the variable is wrong.
If I declare a global variable MyObject (loke var mytimer;) and use it instead this.timer, it works.
This is my code:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title></title>
<script type="text/javascript" language="JavaScript">
var MyObject = {
init: function(){
this.timer = 0;
document.getElementById("btn1").onclick = function(){
MyObject.RunIt();
};
document.getElementById("btn2").onclick = function(){
clearInterval(this.timer);
};
},
RunIt: function(){
var x=0;
this.timer = setInterval(function(){
x++;
document.getElementById("spn").innerHTML=x;
}, 1000);
}
};
</script>
<style type="text/css">
</style>
</head>
<body onload="MyObject.init();">
<input type="button" id="btn1" value="Run"/>
<input type="button" id="btn2" value="Stop"/>
<span id="spn"></span>
</body>
</html>
The problem is this: when you set "onclick" to a function call like that, there's no object reference in the call. The browser calls your function to do the "clearInterval", but "this" is not pointing to your object - in fact, it's pointing at the button element itself.
Here's one way to work around the problem:
var self = this;
document.getElementById('btn2').onclick = function() {
clearInterval(self.timer);
};
I know that question-askers on Stackoverflow get annoyed sometimes when people urge them to investigate jQuery or some other modern Javascript framework, but it's simply a better way to do things.
This is a common problem in writing javascript code; the Scope.
in an .onclick method on an element, the scope (this) is the element itself not the class you are in (MyObject).
i use this/that method; like below:
init: function(){
this.timer = 0;
document.getElementById("btn1").onclick = function(){
MyObject.RunIt();
};
var that = this;
document.getElementById("btn2").onclick = function(){
/**
Here i use 'that' instead of 'this';
because 'this' is the button element
*/
clearInterval(that.timer);
};
},
You can access an object through this only if the object was created by new.
The this in your code refers to the window object. In the event handlers it refers to the respective HTML element.
Read a detailled explanation.
Your MyObject declaration is an object, but lets say that it is not an object instance. There is a difference in JS.
Object instance example:
function MyClass() {
this.timer = 0;
this.RunIt = function() {
var x=0;
this.timer = setInterval(function(){
x++;
document.getElementById("spn").innerHTML=x;
}, 1000);
};
var me = this; // alias to current "this"
document.getElementById("btn1").onclick = function(){
// "this" refers to btn1, use me
me.RunIt();
};
document.getElementById("btn2").onclick = function(){
// "this" refers to btn2, use me
clearInterval(me.timer);
};
}
var MyObject = new MyClass();
Note, that there are many different ways to construct objects in JavaScript.
EDIT: it contains another bug: the event handler functions will be executed as members of the HTML element. So this in the handlers refers to the HTML element, not to your object.
EDIT: fixed the code
EDIT: Bad day, don't listen to me ;-)
Related
How can I refer the the object itself in an event callback defined within an object literal in JS/jQuery please?
I have researched various answers and articles, such as this question: How to access the correct `this` inside a callback? but only found myself more confused.
It makes sense that this should refer to the element that was clicked as we need access to it, but how then do I refer the the object containing the binding function itself?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>This</title>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<button id="test">Click Me</button>
<script>
$( document ).ready( function() {
console.log(MyObj.introspect());
MyObj.bindEvents();
} );
MyObj = {
myProperty : 'a property',
bindEvents : function(){
$('#test').on('click', MyObj.introspect)
},
introspect : function(){
console.log(this);
}
}
</script>
</body>
</html>
In your case, you'd use MyObj, just like you did in bindEvents, since it's a singleton:
MyObj = {
myProperty : 'a property',
bindEvents : function(){
$('#test').on('click', MyObj.introspect)
},
introspect : function(){
console.log(MyObj);
// ---------^^^^^
}
}
Side note: Your code is falling prey to what I call The Horror of Implicit Globals. Be sure to declare your variables (with var, or ES2015's let or const). In your case, you can make MyObj entirely private since you only need it in your own code, by moving it into the ready callback and declaring it:
$( document ).ready( function() {
var MyObj = { // Note the `var`
myProperty : 'a property',
bindEvents : function(){
$('#test').on('click', MyObj.introspect)
},
introspect : function(){
console.log(MyObj);
}
}; // Also added missing ; here
console.log(MyObj.introspect());
MyObj.bindEvents();
});
I am trying to listen to a click event and give the output accordingly.
However, I am a bit confuse on adding events inside an object.
I tried this.
var object1 = {
getVariables: {
button1: document.getElementById('button');
},
eventHandler: {
getVariables.button1.addEventListener('click', this.alertSomething);
},
alertSomething: function() {
alert('Cool');
}
};
Is this a correct way to listen to the events? If not, please help me correct it.
You'll have to save the reference to the variable somewhere in the object - and for the object to reference itself to achieve that, it'll have to use this somehow. (well, you could also pass in the whole object as a separate argument, but that's kinda odd and not often done)
It's somewhat tricky because when calling object1.getVariables.button1, the context of this is the object referenced by the getVariables property, but you likely want to put the information into somewhere more appropriate within object1 itself, not within getVariables. Let's store the variables in a storedVariables property.
We want the functions to be called with a reference to the outer object, not the getVariables or addEventHandler property, so we have to use call to pass a custom this to the functions:
const button = document.getElementById('button');
const object1 = {
storedVariables: {},
getVariables: {
button1: function() { this.storedVariables.button1 = document.getElementById('button') },
},
addEventHandler: {
button1: function() { this.storedVariables.button1.addEventListener('click', this.alertSomething); },
},
alertSomething: function() {
alert('Cool');
}
};
object1.getVariables.button1.call(object1);
object1.addEventHandler.button1.call(object1);
<div id="button">
some button
</div>
It would be notably less convoluted if there was a method such as getButton1 directly on object1 (and the same for addEventHandler), that way they could be called normally without having to customize their this.
Just bind object1 object to this variable.
<!DOCTYPE html>
<html>
<body>
<div id="button1">
Button-1
</div>
<script>
var object1 = {
button1: document.getElementById('button1'),
eventHandler: function() {
this.button1.addEventListener('click', this.alertSomething);
},
alertSomething: function() {
alert('Cool');
}
};
object1.eventHandler.call(object1);
</script>
</body>
</html>
Sorry, probably bit of a noob JS question regarding binding handlers to instances.
I am creating a controller instance with some data that will subsequently be used to process incoming events (the actual use case is composing complex d3 handlers with varying ajax urls and into which I compose the function(s) doing the actual tree update).
RequireJS and jquery are involved, but I suspect my issue has more to do with my specific binding code. I guess I could forego the use of 'this' since I have only one controller per page which can be a global. But this feels like it should be doable, if only I knew how to.
This is how I bind the controller to its target, from within the constructor (doing it outside the constructor seems to work):
function BtnMgr(msg, tgt_id) {
this.msg = msg;
this.tgt_id = tgt_id;
var selector = "#" + tgt_id;
$(selector).on("click", this.handleClick);
}
What is going wrong?
When I click on the button, 'this', in the handleClick refers to the html button, not to the controller instance.
If I call the controller instance method directly, 'this' is correct.
I've tried call or creating a wrapper function, as suggested in
How can I bind an event handler to an instance in JQuery?
$(selector).click(function(e) { BtnMgr.prototype.handleClick.call(this, e); });
My button click keeps seeing 'this' as the button, not the controller:
output
global var controller:BtnMgr.I am a button
this:[object HTMLButtonElement],type:
e:[object Object],type:Object
BtnMgr.handleClick:this.msg:undefined
Simplified version:
HTML
page4.html
<!DOCTYPE html>
<html>
<head>
<title>Page 4</title>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.15/require.min.js"></script>
<script type="text/javascript">
requirejs.config({
baseUrl: '.',
paths: {
"jquery": "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min"
}
});
var controller;
require(["main4"], function(BtnMgr) {
controller = new BtnMgr("I am a button", "btn_click");
//this simulated call works - 'this' refers to the BtnMgr instance
controller.handleClick("dummy_btn");
});
</script>
</head>
<body>
<button id="btn_click">click me!</button>
</body>
</html>
RequireJS
main4.js
define(["jquery"], function($) {
function BtnMgr(msg, tgt_id) {
this.msg = msg;
this.tgt_id = tgt_id;
var selector = "#" + tgt_id;
$(selector).on("click", this.handleClick);
}
BtnMgr.prototype.toString = function(){
return "BtnMgr." + this.msg;
};
BtnMgr.prototype.handleClick = function(e) {
//I want 'this' to refer to the BtnMgr instance
//and e to the html element that got clicked...
console.log("global var controller:" + controller);
console.log("this:" + this + ",type:" + this.constructor.name);
console.log("e:" + e + ",type:" + e.constructor.name);
console.log("BtnMgr.handleClick:this.msg:" + this.msg);
};
//define is returning the constructor method for the object
return BtnMgr;
});
You could achieve (nearly) what you want with :
$(selector).on("click", this.handleClick.bind(this));
this will be the instance of BtnMgr and e.target will, as always, be the button.
However, that would fly in the face of convention and confuse anyone trying to understand your code, including yourself in 6 months time. In a click handler, this should always refer to the clicked element, as is natural.
If you really must have a reference from the handler back to the instance of BtnMgr that attached the click, then I might opt for "e-augmentation" like this :
function BtnMgr(msg, tgt_id) {
var that = this;
this.msg = msg;
this.tgt_id = tgt_id;
var selector = "#" + tgt_id;
$(selector).on("click", function(e) {
e.clickAttacher = that;
that.handleClick(e);
});
}
BtnMgr.prototype.toString = function(){
return "BtnMgr." + this.msg;
};
BtnMgr.prototype.handleClick = function(e) {
console.log("click attacher was instance of : " + e.clickAttacher.constructor.name); // BtnMgr
console.log("button id: " + e.target.id); // xxx
console.log("msg: " + e.clickAttacher.msg); // Hello World!
};
var b = new BtnMgr('Hello World!', 'xxx');
DEMO
Having done that, you have to ask whether it's really worthwhile defining handleClick in that way. Sure, if it's a monster function then yes, define it with BtnMgr.prototype...., but if it's only small, then define it in the constructor itself and take direct advantage of that being in the scope chain (as does the augmenter function above).
Try this when you bind your onClick:
function BtnMgr(msg, tgt_id) {
this.msg = msg;
this.tgt_id = tgt_id;
var selector = "#" + tgt_id;
$(selector).on("click", $.proxy(this.handleClick, this));
}
That would make sure that the 'this' variable in your callback is your class and not the clickevent.
You can read more about jQuery Proxy here: http://api.jquery.com/jquery.proxy/
What am doing wrong. I try to make object but when i try to initialize i get this error in console: I try to put all in document.ready and whitout that but dont work. In both case i have some error. Am new sorry for dumb question
ReferenceError: Circle is not defined
var obj = new Circle;
JS
$(function(){
var Circle = {
init: function() {
console.log("Circle initialized");
}
};
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="javascript/circle.js"></script>
<script>
$(document).ready(function(){
var obj = new Circle;
obj.init();
})
</script>
</head>
<body>
<div id="test" >TODO write content</div>
</body>
</html>
NEW UPDATE
$(function(){
window.Circle = {
init: function() {
console.log("Circle initialized");
}
};
window.Circle.init();
});
....
<head>
<script>
window.Circle().init();
</script>
</head>
You've defined your "Circle" function inside another function — the anonymous function you pass in as a a "ready" handler. Therefore, that symbol ("Circle") is private to that function, and not visible to the other code.
You can make it global like this:
window.Circle = {
// ...
};
You could also add it to the jQuery namespace (may or may not be appropriate; depends on what you're doing), or you could develop your own namespace for your application code. Or, finally, you could consider combining your jQuery "ready" code so that the "Circle" object and the code that uses it all appears in the same handler.
edit — another possibility is to move your "Circle" declaration completely out of the "ready" handler. If all you do is initialize that object, and your property values don't require any work that requires the DOM or other not-yet-available resources, you can just get rid of the $(function() { ... }) wrapper.
1) you are assigning Circle in a function context, not as a global. You can only use it there unless you expose it to global.
2) you are calling Circle as a constructor, but Circle is not a function.
This solves both issues:
var Circle = function () {};
Circle.prototype.init = function () {
console.log('Circle initialized.');
};
var obj = new Circle();
obj.init();
I have the code below. I would like to have an array (buttons) with a single element pointing to the a function (closeFlag).
<script type="text/javascript">
var closeFlag = new function() {
alert('Clicked');
}
var buttons = {
'OK': closeFlag
}
</script>
However, when loading the page the alert immediately pops up. When the array is constructed, instead of using it as a pointer, JavaScript calls my function.
Why? What mistake, misconception do I have?
The new keyword, you will not need it.
<script type="text/javascript">
var closeFlag = function() {
alert('Clicked');
}
var buttons = {
'OK': closeFlag
}
</script>
What's happening in your code is that it's constructing the anonymous function then assigning the result of it (this) to closeFlag.