I need to call the object showMe() method from a child object, when debugging the this does not recognize the showMe() method.
How can I reference an object method from within the method ???
code follows -
function myObj(n) {
this.name = n;
this.frame = $('<div />');
var subFrame = $('<div />');
subFrame.on("click", function () {
**//how do I reference this.showName() from here ?**
});
this.frame.append(subFrame);
this.showName = function (nn) {
alert(nn);
};
}
$(function () {
var a = new myObj("Test");
});
A common way to do this is to define var that = this, and refer to that in the function body.
You could also use bind, but then you give up the local scope.
You can actually just pass a reference to the object into on() as data,
function myObj(n) {
this.name = n;
this.frame = $('<div />');
var subFrame = $('<div />');
subFrame.on("click", {myObj : this}, function (e) {
e.data.myObj.showName();
});
this.frame.append(subFrame);
this.showName = function (nn) {
alert(nn);
};
}
$(function () {
var a = new myObj("Test");
});
FIDDLE
Related
So i need to get the inner text of a given element through a Jquery event, and then set this text into a member of my class e.g.
myClass = function ()
{
this.index = 0;
this.onNavElementClick = function ()
{
this.index = parseInt(this.text());
}
this.myMain = function ()
{
$("nav#wow-so-much-inspiration").on("click", "a", this.onNavElementClick);
}
}
myObject = new myClass();
myObject.myMain();
HTML:
<nav id="wow-so-much-inspiration">
1
2
3
</nav>
But this won't work because of the two different scopes inside the onNavElementClick() function... And i don't like the idea of doing _this = this, i'm pretty sure there is a right way to do that without doing MacGyver coding.
jQuery event handlers also take the event object (including the target on which the event was triggered) as a first argument. Then you can use $.proxy to have your event handler bound to the outer this.
Something like this:
this.onNavElementClick = $.proxy(function (e)
{
this.index = parseInt($(e.target).text());
}, this);
You could make use of the bind method, but I believe this has been proven to have minor performance implications.
Example - which is essentially what the $.proxy answer does.
var myClass = function ()
{
this.index = 0;
this.onNavElementClick = (function (event) {
this.index = parseInt( $(event.target).text() );
}).bind(this);
this.myMain = function ()
{
$("nav#wow-so-much-inspiration").on("click", "a", this.onNavElementClick);
};
}
var myObject = new myClass();
myObject.myMain();
Another option is to use call or apply with a simple wrapper function.
var myClass = function ()
{
this.index = 0;
this.onNavElementClick = function (event)
{
this.index = parseInt( $(event.target).text() );
};
this.myMain = function ()
{
var self = this;
$("nav#wow-so-much-inspiration").on("click", "a", function (event) {
self.onNavElementClick.call(self, event);
});
};
}
var myObject = new myClass();
myObject.myMain();
Define onNavElementClick as a var within the my class constructor and reuse the function as needed.
var onNavElementClick = function(){...};
I can't get how to access that value, this is my code:
function Filters()
{
this.filters = ["filter_1", "filter_2", "filter_3"];
this.someData = "test";
this.draw = draw;
function draw(){
for(var i=0; i<this.filters.length;i++)
{
var filter = this.filters[i];
$("#" + filter).click(function(){
doSomething();
});
}
}
function doSomething(){
alert(this.someData);
}
}
I am aware of the fact that since doSomething() is called from within the closure, this. will refer a JQuery object being worked on. So how do I go about being able to use someData from my object in that function/closure ? Can't seem to figure it out.
Thanks for help :)
No, this inside doSomething will be the global object. You need to keep a reference to this in a separate variable:
function Filters()
{
var that = this; // reference to this
this.filters = ["filter_1", "filter_2", "filter_3"];
this.someData = "test";
this.draw = draw;
function draw(){
for(var i=0; i<this.filters.length;i++)
{
var filter = this.filters[i];
$("#" + filter).click(function(){
doSomething();
});
}
}
function doSomething(){
alert(that.someData);
}
}
Unrelated to your problem: you could also pass a reference to doSomething as the event listener, instead of wrapping it in another function:
$("#" + filter).click(doSomething);
I have the following class in javascript:
function User(aJid){
this.jid = aJid;
this.name = '';
this.uni = '';
this.edad = '';
this.foto = '';
this.avatar = '';
this.initialize2 = function(){
$('#edit_vcards').on('click', '#enviar_vcard', function(){
//alert("enviando...");
console.log(this);
});
};
As you can see I have a method "initialize2" that binds a function to some elements in the DOM. In there I do a console.log(this) which prints the DOM element we binded the method to and not the object that is executing the method initialize2. How can I have access to that object from that function?
Its like if the scope of the function binded is the whole DOM and not the object. Anyway to do what Im trying to do ?
function User(aJid){
this.jid = aJid;
this.name = '';
this.uni = '';
this.edad = '';
this.foto = '';
this.avatar = '';
this.initialize2 = function(){
var that = this; //store a reference to maintain scope
$('#edit_vcards').on('click', '#enviar_vcard', function(){
//alert("enviando...");
console.log(that); //use that variable here
});
};
Try passing the obj this to .on and the inside the handler you can use event.data to access the obj this. See below,
this.initialize2 = function(){
$('#edit_vcards').on('click', '#enviar_vcard', {obj_this: this }, function(){
//alert("enviando...");
console.log(event.data.obj_this); //should be the obj this
});
};
Pass the outer this through event.data:
$('#edit_vcards').on('click', { outerThis: this }, function (event) {
console.log(event.data.outerThis);
});
Nowadays with ES6 it can be even more elegant
$('#edit_vcards').click( () => {
//alert("enviando...");
console.log(this); // all your variables are availabled here
});
or even like that (if you need only one line):
$('#edit_vcards').click( () => console.log(this) );
NOTE: This code cannot be used directly and should be additionally compiled with balel, for example.
I have this:
function test1()
{
this.count = 0;
this.active = 0;
this.enable = function () {this.active = 1;}
this.disable = function () {this.active = 0;}
this.dodo = function ()
{
$("html").mousemove(function(event) {
// I want to get here the "active" param value;
});
}
this.enable();
this.dodo();
}
instance = new test1();
instance.disable();
Let's say I want to check the active param of the test1 class in the commented place. How can I get it there ?
Thanks!
If you want access to all the member variables of the higher scope, you just need to save the this pointer from that scope into a local variable so you can use it inside the other scope:
function test1() {
this.count = 0;
this.active = 0;
this.enable = function () {this.active = 1;}
this.disable = function () {this.active = 0;}
var self = this;
this.dodo = function () {
$("html").mousemove(function(event) {
// I want to get here the "active" param value;
alert(self.active);
});
}
this.enable();
this.dodo();
}
instance = new test1();
instance.disable();
this.dodo = function ()
{
var active = this.active;
$("html").mousemove(function(event) {
alert(active);
});
}
When you call a function 'this' refers to the object the function was invoked from, or the newly created object when you use it together with the keyword new. For example:
var myObject = {};
myObject.Name = "Luis";
myObject.SayMyName = function() {
alert(this.Name);
};
myObject.SayMyName();
Note in JavaScript there are multiple ways to declare, define, and assign fields and methods to objects, below is the same code written more similarly to what you wrote:
function MyObject() {
this.Name = "Luis";
this.SayMyName = function() {
alert(this.Name);
};
}
var myObject = new MyObject();
myObject.SayMyName();
And yet another way to write the same thing:
var myObject = {
Name: "Luis",
SayMyName: function() {
alert(this.Name);
},
};
myObject.SayMyName();
There are also several different ways to invoke a function.
I've got a big Javascript project that I'm trying to refactor into pseudo-classes:
jsFiddle: http://jsfiddle.net/waitinforatrain/7T42w/
var MyNameSpace = {}
MyNameSpace.MyClass = function() {
this.doSomething = function () {
return "hello";
}
this.doSomething2 = function() {
var x = this.doSomething() + " world";
alert(x);
}
this.doSomething2(); //Works fine
$("#mydiv").click ( this.doSomething2 ); //Doesn't work
}
var class = new MyNameSpace.MyClass();
The reason the click event causes an error is that this refers to the #mydiv element.
How am I supposed to design the above so that I can access the element that was clicked but can also call doSomething()?
You need to cache the context reference and wrap the call in a closure:
var MyNameSpace = {}
MyNameSpace.MyClass = function() {
var context = this;
context.doSomething = function () {
return "hello";
}
context.doSomething2 = function() {
var x = context.doSomething() + " world";
alert(x);
}
// You can do this:
context.doSomething2();
// Or this:
$("#mydiv").click(function(e) {
context.doSomething2();
});
}
this.doSomething2 = $.proxy(function() {
var x = this.doSomething() + " world";
alert(x);
}, this);
$.proxy binds the this scope to the context variable inside said function.
Save a reference to this in the outer scope:
MyNameSpace.MyClass = function() {
var that = this;
this.doSomething = function () {
return "hello";
}
this.doSomething2 = function() {
var x = that.doSomething() + " world";
alert(x);
}
this.doSomething2(); //Works fine
$("#mydiv").click ( this.doSomething2 ); //Doesn't work
}
The function assigned to doSomething2 is said to "close over" the variables in its lexical scope and so has access to their values even once MyClass has returned. This allows us to access the doSomething method through the reference to the instance we assigned to that.