I have created a DOM structure like this
<div data-execute="someFunction.abc" id="someId">
</div>
I am able to retrive the attribute in js but I intend to execute this as a callback function. So I am doing like this
var x = document.getElementById("someId").getAttribute('data-execute');
As expected this is returning someFunction.abc .But on consoling typeof(x) it is showing "string".Please refer to this fiddle
var someFunction = function() {
alert("Hello")
}
var load = (function(module, global) {
var x = document.getElementById("someId").getAttribute('data-execute');
console.log(typeof(x))
}(load || {}, this))
<div data-execute="someFunction.abc" id="someId">
Some Function
</div>
I also checked this link
Passing a Javascript function through inline data- attributes
But no way I am able to execute it as a call back function.Any help will be truly appreciable.
Try this:
<div data-execute="someFunction.abc" id="someId"></div>
var x = document.getElementById("someId").getAttribute('data-execute');
window[x].call();
You can use the call methodon the function defined in the global scope, you can access it in the global window ojbect.
Ref:
The call() method calls a function with a given this value and
arguments provided individually.
I have assumed the code after the point is a paramter to pass to the function.
Code:
var someFunction = function (p) {
alert(p)
}
var load = (function (module, global) {
var x = document.getElementById("someId").getAttribute('data-execute');
window[x.split('.')[0]].call(undefined, x.split('.')[1]);
}(load || {}, this))
Demo: https://jsfiddle.net/IrvinDominin/5bjsmu3x/
Related
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;
});
}
I wanted to define the input values from HTML page as javascript Literal object property but i am getting Undefined error on accessing in JS file.
Suppose i have a input value like as in HTML
<input type="hidden" id="someid" value="dbvalues in arrayform" >
Now this value i am trying to define like (A.js) as below:
var abc = {
x : $("#someid").val(),
y: function (){
console.log(this.x);
}
}
Now when in another JS file (B.js) i call it as
console.log(abc.x());
Any Solutions?
A.js
var abc;
$(function() {
abc = {
x: $("#someid").val(),
y: function (){
console.log(this.x);
}
}
});
B.js
$(function() {
abc.y();
});
Note that $("#someid").val() will return a string, so you may need to convert into into an array.
x is not function, it is string.
You should call it as:
console.log(abc.x);
two things - first of all it would not be console.log(abc.x()); x() is how you call a function, you could call abc.y(); though since it's a function.
the other thing is that jQuery must be loaded, and that this code defining var abc = { has to be executed after the DOM is fully loaded
I think you want this:
$(function(){ // this ensures DOM is ready, careful about where you want to call abc from though;
var abc = {
var me = this;
x : function(){ return $("#someid").val()},
y: function (){
console.log(me.x); // try this instead it will help with 'this' confusion
}
}
});
now you can call
console.log(abc.x());
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);
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);
});
Can anyone tell me why my 'showDiv_boo' is undefined inside the class´s method?
I also can´t access my class´s methods.
Here´s my class 'Blink' class with its properties and methods:
function Blink(div) {
this.div = div
}
Blink.prototype.counter = 0
Blink.prototype.showDiv_boo = true
Blink.prototype.showDiv = function() {
this.div.style.visibility = 'visible'
}
Blink.prototype.hideDiv = function() {
this.div.style.visibility = 'hidden'
}
Blink.prototype.startEngine = function() {
if (this.showDiv_boo) {
this.showDiv()
} else if (!this.showDiv_boo) {
this.hideDiv()
}
this.showDiv_boo = !this.showDiv_boo
this.counter++
}
Blink.prototype.startEffect = function() {
this.idEffect = setInterval(this.startEngine, 1000 / 45)
}
So, if I create:
_blink = new Blink(myDiv);
_blink.startEffect();
You can test... the variable 'showDiv_boo', is undefined inside the method.
Even, if I set the showDiv_boo inside the method to true, it won´t call my class´s methods showDiv or hideDiv.
Anyone?
Thanks :)
The reason why is that startEngine is called from setInterval. The way in which this callback is invoked causes startEngine to have a different value for this than startEffect. You need to save this in order to maintain it in the callback. For example.
Blink.prototype.startEffect = function () {
var self = this;
self.idEffect = setInterval(function () { self.startEngine(); }, 1000 / 45);
};
You need to:
use var self and call the method via self.startEngine()
use an anonymous function to wrap the call in [1] i.e. function(){ self.startEngine(); }
This is because when you just pass this.startEngine or self.startEngine you are just passing the function startEngine without specifying what this is, which in both cases is supplied by the global conext of DOMWindow.
To give an example...
function startEngine() {
...code omitted...
};
Blink.prototype.startEngine = startEngine;
Blink.prototype.start = function() {
setTimeout(startEngine, 0); // obviously wrong, what is this?
setTimeout(Blink.startEngine, 0); // actually the same as line above, although not as obvious
setTimeout(startEngine.bind(this), 0); // works correctly
}
works to add code to the prototype and if used in the anonymous function will work as expected, but if you just use Blink.startEngine as the callback it is exactly the same as using startEngine only the second is more obviously wrong because there's no object it is being called on so you'd expect this to be whatever is supplied by the context.
The other way you could do this without using the anonymous function would be
Blink.startEngine.bind(self)
Which returns a function that will call startEngine with the correct this same as explicitly creating the anonymous function and wrapping the call to self.startEngine()
Heres a link to a fiddle to play around with the differences: http://jsfiddle.net/bonza_labs/MdeTF/
If you do the following, you will find it is defined
var x = new Blink('hello');
x.showDiv_boo
Javascript uses prototypical inheritance. While showDiv_boo may not be explicitly defined within the instance of Blink that you now have, it does exist within the prototype that Blink inherits from. When you try referencing showDiv_boo from within the object, the Javascript engine realizes the object does not own a member by that name and then will check its prototype.
Along with setting a temporal variable to store this, you must call the startEngine() function with that variable:
Blink.prototype.startEffect = function(){
var self = this;
self.idEffect = setInterval(function(){ self.startEngine.call(self); }, 1000/45);
}
Note the .call(self), which basically calls the function with the variable self, so the variable this in startEngine will be the correct one.