Call a function inside a custom data-attr? - javascript

Given a current CMS we are working in, I need to call functions within a custom data-attribute. Is it possible to call the contents of a data attribute as a function to run like below? Simple example:
Set
<button data-function="alert('hello world')">Run Function</button>
Run
$('button').attr('function');
I believe the above is just getting the contents and not actually executing anything when written.
Is this possible?

You could create a Function from the data attribute:
// create
var funcStr = $('button').data('function');
var f = new Function(funcStr);
// invoke
f();
See MDN

This is another approach if the function is known.
$(document).ready(function() {
$('button').click(function() {
var functionObject = JSON.parse($('button').attr('data-function'));
window[functionObject.name].apply(window, functionObject.arguments);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button data-function='{"name": "alert", "arguments" : ["hello world"]}'>Run Function</button>
It parses the JSON string from the data-function attribute. Call the function provided by name using the window object (eliminating eval) and passes the arguments (inside an array) to the function using apply.

If you want to execute the code, you will have to call eval. You also need to use the full name of the attribute, or use .data().
eval($('button').attr('data-function'));
or
eval($('button').data('function');

You can always use eval function.
eval($('button').attr('data-function'));

Related

"this" keyword is not working inside jquery function

I want to use "this" keyword within my jquery function but it doesn't works for me...
i have tried following ways:
1...
Not works....
function getRequest() {
var ReqPlace = $(this).parent('div.reqHere').parent('div.allReqs').children('div.reqHere');
}
2..
Not works....
var that=this; //also tried var that=$(this);
function getRequest() {
var ReqPlace = $(that).parent('div.reqHere').parent('div.allReqs').children('div.reqHere');
}
3..
Works but this time i have used a button
<input type="button" onclick="getRequest(this);" />
function getRequest(that) {
var ReqPlace = $(that).parent('div.reqHere').parent('div.allReqs').children('div.reqHere');
}
The above 3rd step is works pretty good but i don't need a button Is there any other way to use "this" keyword inside function
Thanks
this returns the instance of the object in which it was called.
In your case it does not work in statement 1 because for some reason you called this out of nowhere and returns you the instance of the function instead that is why it is not working
Same goes to statement 2 consider if the declaration
var that = this;
if this is inside a function this will return a function as well that is why it is not working.
And finally the reason statement 3 is working is it's returning the html object instance of the element since the function is a click event listener of an element. Take note that calling this in the function using statement 3 will work as well.
Well you can always use this in a function but remember that
$(query)
jQuery(query)
where query is an HTMLObject or an html string or a css selector string, sending it with a function will cause an error.
If you want to do something like this code inside a function
$(this).parent('div.reqHere').parent('div.allReqs').children('div.reqHere');
unless this is an HTML Object, what you should do is:
<div class='somedivinyourtemplate' id='hello'>
</div>
function () {
$('#hello').parent('div.reqHere')
.parent('div.allReqs').children('div.reqHere')
}
or just simply put an id of the element you want to select.
Hope that helps you understand how it works
if you want to use "this" in jquery
give id to button
<input type="button" id="getrequest" />
then
$("#getrequest").click(function(){
$(this).parent('div.reqHere').parent('div.allReqs').children('div.reqHere')
})

JS - Running a jQuery function with a variable name

I need to run a function with a part dynamic variable in it's name.
The function to run:
$.element_gallery = function(state){}
The code that's calling it:
var name = "gallery";
window["$.element_"+name]('refresh');
This method seems to work with traditional Javascript functions but not with a jQuery function. Is there a way to run this without using eval() and without changing the function name?
Replace window with $
$["element_" + name]("refresh")
When you do window["$.foo"] it's looking for a property on the window object that's called $.foo. However, if you're using a jQuery function it's stored in the jQuery (or $) property of the window object, so the actual location of the function you want is window.$["foo"]. Change your code to:
var name = "gallery";
window.$["element_"+name]('refresh');
Or, since you can access global variables without specifying window., just:
var name = "gallery";
$[".element_"+name]('refresh');

JavaScript: how to pass object value from one function to another

I am using code lines like the following in order to fetch data from an intranet website:
util.setProp(obj, "firstNameOld", $(msg).find('#fname_a').text());
Now I have another function in the same file where I want to use the above again, resp. the value of that object - currently I am hard-coding this ('Test') for test purposes:
util.setProp(obj, "firstNameNew", 'Test');
How can I pass the value from the firstNameOld object in one function to the firstNameNew object in another function ? If a solution with global variables is better here than this would work as well.
Many thanks for any help with this, Tim.
I've never used the framework that includes util But I imagine that if there is a setProp() then there has to be a getProp() or something similar.
If so, you could do something like
util.setProp(obj, "firstNameNew", util.getProp(obj, "firstNameOld"));
This also relies on the assumption that you want to copy from two properties in the same object.
If not, then pass the desired source object in the getProp() call.
My guess is that functions (or properties) are called "firstNameOld" and "firstNameNew", so the first time you get it from selector, second time you want to do the same.
Try to use the local variable like that:
var text = $(msg).find('#fname_a').text();
//
util.setProp(obj, "firstNameOld", text);
//
util.setProp(obj, "firstNameNew", text);

Javascript creating references to native functions

I have written this code (this is a snippet) that doesn't seem to be working. I have isolated it to here.
grab = window.document.getElementById;
grab("blueBox") // i.e. grab("blueBox").onclick [...]
Is it possible to create references to native function in javascript. I am doing something with the grabbed element, I just left it out for example. The grab function doesn't seem to work.
I am using FireFox's most recent version
The way you're doing it will mess up the assignment of the this value for the function.
grab = window.document.getElementById;
grab("blueBox") // i.e. grab("blueBox").onclick [...]
here this will be the global object. Try:
grab.apply(window.document, ["blueBox"])
or in newer browsers:
grab = window.document.getElementById.bind(window.document);
to get directly define what this will be.
The first step here is always the JavaScript console. Firebug is your friend. Tell us the error message if it doesn't mean anything to you.
In the mean time, here is a workaround:
var grab = function(id) { return window.document.getElementById(id); }
function grab(id) {
return window.document.getElementById(id);
}
grab("blueBox");
The reason is because the function getElementById is not being called as a method of document, so its this keyword doesn't reference the right object. Using call as suggested in other answers shows that when this references the document, getElementById works.

Passing Variables Javascript

I am trying to pass a variable in javascript. I create a link in the following manner and everything seems to be working.
label.innerHTML = ' link';
However when I create the link in the following way where the link would also pass an associated object I get the following error from firebug -> "missing ] after element list"
label.innerHTML = ' link';
Is this an acceptable way to pass an object to a function. The problem is that I am creating this link within a function. The function creates links like this based upon an object that is passed to it. Therefore I cannot have this "object" as a global scope.
You are building the script by mashing together strings, as such you can only work with strings and object will be automatically stringified.
Use DOM instead.
var link = document.createElement('a');
link.href = "#"; // Have a more sensible fall back for status bar readers and middle clickers
link.appendChild(document.createTextNode(' link');
link.addEventListener('click',function () { show_box(this, object); },false);
label.appendChild(link);
… but use a library that abstracts away the non-standard event models that some browsers have.
What you're trying to do is pass the contents of object to output. Since it's an object, the string representation will be something like [object Object]. The output HTML would look like:
link
which is invalid. Don't try to concatenate the object, just pass it along as another argument to the function, like this. Or, better yet, use jQuery:
<!-- somewhere in the head, or at least after the object is defined -->
<script type="text/javascript">
$(function() {
$('#thelink').click(function() { show_box(this, object); });
});
</script>
...
link
If your object is simple variable like numeric or string variable than it will be Ok but if you are passing html object it will not work because it will be something like below.
link

Categories