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

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);
})
}

Related

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

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));
});

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')"

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;
});
}

JavaScript global variables declaration

The following script works correctly although I need to make few amends. In each function I am getting the values need for the different formulas. However I tend to replicate the same line of code in different functions.
Ex.
function one(){ var v1= document.getElementById('one').value; }
function two(){ var v1= document.getElementById('one').value; }
Full code
I would like to declare all of the variables once and than only use the ones I need for the specific functions. If I declare them right at the top than once they are called they still hold the original value so I need to update that value to the current one if changed of course.
Your code will be very hard to read if you do it like in your fiddle.
Instead do
var myVars;
window.onload=function() {
myVars = {
'list_price': document.getElementById('list_price'),
'negotiated': document.getElementById('negotiated'),
.
.
'lease_payment': document.getElementById('lease_payment')
}
now you can do
var price = myVars.list_price.value;
or perhaps add a function
function getVal(id) {
var val = document.getElementById(id).value;
if (val =="" || isNaN(val)) return 0;
return parsetInt(val,10);
}
now you can do
var price = getVal("list_price");
mplungjan's solution is a great one. If you're at all concerned by your global vars leaking into the window scope, wrap your code in an Immediately Invoked Function Expression to prevent that from happening:
(function(){
// code goes here
}());
There are two ways to go about this:
Update your variable when the value changes
Use a function that always returns the correct value
1) You can add a listener for the change event or the keyup event that changes your global variable:
// save initial value
var val = document.getElementById('one').value;
// update the value when input is changed
addEventListener(document.getElementById('one'), 'change', function() {
val = document.getElementById('one').value;
});
console.log(val);
2) You can use a function that always returns the current value:
var val = function() { return document.getElementById('one').value; };
console.log(val());
2b) If you hate parenthesis, you can define a property that uses the function above as a getter:
Object.defineProperty(window, 'one', {
get : function() { return document.getElementById('one').value; }
});
console.log(one);

Properly wrapping functions in JavaScript

I have the following problem:
I have a function
workspace.func = function() {console.log(5);}
I attach it as an event handler:
$(workspace).bind("ping", workspace.func);
Then, I change the function definition:
var cF = workspace.func;
workspace.func = function() {
...
cf.call(this);
}
but
$(workspace).trigger("ping")
>>5
How can I properly wrap the function at runtime, so that the handler points to the changed one as well?
You can do it like this:
workspace.func = function() {console.log(5);}
$(workspace).bind("ping", function() {workspace.func()});
var cF = workspace.func;
workspace.func = function() {
...
cf.call(this);
}
After reassigning the value of workspace.func, the ping event handler will go to the new function because it gets the function pointer from the variable and then executes it so if you change which function that variable points to, it will pick up the new value - unlike your original version which had a reference to the actual function so changing the workspace.func variable didn't do anything.

Categories