How to get current object reference inside a jquery callback function? - javascript

I have a javascript Object called aObject and a fucntion inside it is used as a jQuery Callback function like this:
var aObject = {
aVariable : 'whatever value',
test : function(e) {
// Trying to access property. But doesn't work as expected since I am getting the DOM element i.e form, not the aObject reference
var temp = this.aVariable;
}
}
$('document').ready(function(){
$('#some-html-form').submit(aObject.test);
});
When I call the test method in aObject, this refers to the form element that has been submitted. I want to access current object from the test callback function?
I tried the below code as described in this answer but it did not work for me
$(document).ready(function() {
$('#add_api_form').submit(api_cahce.handle_add_form_submit.bind(this));
});

bind with aObject then you can access the variable.
var aObject = {
aVariable : 'whatever value',
test : function(e) {
var temp = this.aVariable;
}
}
$('document').ready(function(){
$('#some-html-form').submit(aObject.test.bind(aObject));
});

Related

Set value of element using an input variable

I have a js function that sets the value of id_2 based on the value of id_1. It looks like this below:
function set_value(id_1, id_2, url){
var id_1_value;
id_1_value = $(id_1).val();
var value;
...
/* calculation etc. */
document.getElementById(id_2).value = value;
};
The function is linked to the id_1 html element by an onchange method like this onchange='set_value(this, id_2)'.
If I change the value in id_1 the function doesn't work and I get the following error in the console:
Unable to set property 'value' of undefined or null reference
but if I hardcode document.getElementById('id_2') in the function it works fine. How do I write this function so I can pass an element id variable to it successfully? I want to reuse this function for different elements you see...
Your set_value function should be as below.
function set_value(id_1, id_2, url) {
var id_1_value = $(id_1).val();
/* calculation etc. */
if ($(id_2).length !== 0)
{
$(id_2).val(id_1_value);
}
}
Are you passing "#id_2" to the set_value parameter?
if so that means it would return null.
// The function should be called like this
var id_2 = "id_2";
set_value(this, id_2, blah...)
Change the call like this
onchange='set_value(this, "id_2")'
Second parameter should be passed as string.
try this following code:
function set_value(id_1, id_2, url){
var id_1_value = $(id_1).val();
var value;
...
/* calculation etc. */
document.getElementById(id_2).value = value;
};
and onchange function
onchange="set_value(this, 'id_2')"

How do you use Javascript constructor methods in a jQuery statement?

I can't figure out how to use a Javascript constructor method in a jQuery .click method. I'm trying to get a button's function to change dynamically based on a constructor. Here's the set up:
<button onclick="">
</button>
needs to call a method that changes depending on another button. The following is my broken code:
function GloveMode (name , array) {
this.colorArray = array;
this.displaySettings = function(){
//Title
$("#displayTitle").text(this.name);
//Display Color Set
$("#displayColors").empty();
//Totally Broken
$("#upArrow").click( function(){
addColor();
});
};
this.addColor = function(){
console.log(this.colorArray.length);
};
};
I can't figure out how to get $("#upArrow").click() to call this.colorArray properly, or how to call this.addColor() in the .click() method! Please help.
Your Problem is that "this" means something different in each function body. So save the wanted "this" to a variable e.g. "self" and use that.
function GloveMode (name , array)
{
var self = this;
this.colorArray = array;
this.displaySettings = function()
{
//Title
$("#displayTitle").text(this.name);
//Display Color Set
$("#displayColors").empty();
//Totally Broken
$("#upArrow").click( function()
{
self.addColor();
});
};
this.addColor = function()
{
console.log(self.colorArray.length);
};
};

Setting "this" to the instance, in a callback set during the creation of a prototype function

I have this code:
var createAllAreSelectedClickedHandler = function(selectablesArrayGetter) {
return function() {
var array = selectablesArrayGetter();
var desiredState = array.every(function(selectable) { return selectable.selected; }) ? false : true;
array.forEach(function(selectable) {
selectable.selected = desiredState;
});
};
};
Followed by this one:
function PromoViewModel() { this.registrations = [...] }
PromoViewModel.prototype.allEventsSelectedClickedHandler = createAllAreSelectedClickedHandler(function() { return this.registrations; }));
I can't manage to set the correct value of this. The "this" value when the function is created points to Window so I can't do .bind(this). I've tried doing .bind(PromoViewModel.prototype) but it lacks all the precious instance fields set inside the constructor.
I know I could simply set this.allEventsSelectedClickedHandler in the constructor function, but I'm trying to separate the methods creation from the variables.
The problem is the call selectablesArrayGetter(); which determines the this value for the callback.
You will need to "pass" the this value that the method (i.e. the closure you are returning) is invoked on, using call:
var array = selectablesArrayGetter.call(this);
I'd recommend defining your PromoViewModel.prototype.allEventsSelectedClickedHandler method as follows:
PromoViewModel.prototype.allEventsSelectedClickedHandler = function() {
var _array = this.registrations;
var desiredState = _array.every(function(selectable) { return selectable.selected; }) ? false : true;
_array.forEach(function(selectable) {
selectable.selected = desiredState;
});
};
the function that you're passing as callback uses this, but doesn't have the PromoViewModel context. You can ensure the method has the proper context by binding this to a variable.
function PromoViewModel()
{
var me = this;
this.registrations = [...];
this.allEventsSelectedClickedHandler = createAllAreSelectedClickedHandler(function() {
return me.registrations;
});
}
Working fiddle: http://jsfiddle.net/michaschwab/coegnL5j/9/ also has Bergi's answer in there (commented out) to show that that works just as well.
Ok here is what I did.
In the prototype definition instead of directly associating it to createAllAreSelectedClickedHandler function, I actually define a function that returns the createAllAreSelectedClickedHandler function. By doing this, I can define a variable (in this case protoScope) that maps this context when defined.
When doing that, if you put a break-point in the createAllAreSelectedClickedHandler function you will see that the selectablesArrayGetter value is correct (the acutal registrations array).
PromoViewModel.prototype.allEventsSelectedClickedHandler = function (){
var protoScope = this;
return createAllAreSelectedClickedHandler(function() {
return protoScope.registrations;
});
}

How to change external function variable from internal jquery event function?

How I can change external function variable from internal function?
Example:
function ExternalFunction() {
var $element = $('#my-element'); // Some jquery object
var my_variable = 'value';
$element.click(function() {
// Here I want to change "my_variable" value.
// But I can't change it with "my_variable = 'new value';".
})
}
How I can change my_variable in internal function?
Update1:
I haven't error, but I can't change variable from internal function. See example please:
http://jsfiddle.net/ye0qhu0v/4/
you cant use ExternalFunction() inside DOM ready,Declare the function outside DOM ready
Works perfectly,
function ExternalFunction() {
var $element = $('#my-element'); // Some jquery object
var my_variable = 'value';
$('#my-element').on('click', function() {
// Here I want to change "my_variable" value.
// But I can't change it with "my_variable = 'new value';".
my_variable = 'new value';//here we are assigning new value to the variable
console.log(my_variable);
})
}

Javascript convert string to be called as function

I have the following scenario where I need to call a function based on the data attributes of the html element.
function func1(arg1){
alert("func1");
}
function func2(arg2){
alert("func2");
}
jQuery(document).on('click', '.func-class', function(){
var funcName = jQuery(this).data('func-name');
var funcArg = jQuery(this).data('func-arg');
//Need to call funcName(funcArg) here
});
HTML:
<div data-func-name="func1" data-func-arg="arg1" class="func-class">Func1</div>
<div data-func-name="func2" data-func-arg="arg2" class="func-class">Func2</div>
JSFiddle of the same:
http://jsfiddle.net/E4HeT/
If those functions are defined in ths global scope, you can do this:
window[funcName](funcArg);
Otherwise, I would suggest putting them in an object like so:
var functions = {
"func1":func1,
"func2":func2
};
functions[funcName](funcArg);
This second one is actually safer, as it helps prevent arbitrary code execution.
you can do like the following this
window[funcName](funcArg)
but you will have to get the reference of the function by setting it in a object for example (like what i did in the window object) because its private in the jQuery.ready function
$('.func-class').click(function(){
var toCallArg = $(this).data('func-arg');
var toCall = function(toCallArg){
//your code
};
toCall(toCallArg);
});

Categories