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');
Related
I am able to call function in my code.. however I want to make my calling function name as variable so that it can call any function based on my variable value ..
reportPage.accounts()['catType']()
so here I want to make catType as variable, so that I can pass any value.. How to declare/call here..
You replace the string literal with the variable, exactly as you would anywhere else.
var thing = 'catType';
reportPage.accounts()[thing]()
I have a bunch of CSS properties stored in a MySQL database accessed via PHP. I need to make these properties available to JavaScript after the page has finished loading.
So what I did is foreach row, put the values in a Javascript object like so:
foreach ($cellcontent as $cellproperty) {
echo 'var '.$cellproperty->cell_id.' = {cellwidth:"'.$cellproperty->cell_width.'"};';
}
(For simplicity's sake I've only included one object property here but in reality there are many more.)
My problem is that at runtime, via JavaScript I get the cell_id reference which is somewhere in the html page like so:
var dacell = $(this).closest("div");
var cellid = dacell.attr("id");
So at this point, cellid is equal to the name of my var from the php output.
But when I try to get the property of my object (cellwidth) via JavaScript it doesn't work. Says its undefined when I try to see the value in an alert:
alert(cellid.cellwidth);
I think I'm just not referencing the actual object at this point and just trying to get a property of what has now become a string.
Is there a way to get back the reference to the object itself?
var cellid = dacell.attr("id");
The variable cellid is a string. Your hopes would be that the variable your are looking is in the global namespace which you can access via the following:
window[cellid].cellwidth
It's an awfull practice to pollute the global namespace with so much stuff.
Fetch all the values you need to inject into the JS, create an associative Array and inject it as a single JSON into the Page.
Nevermind everyone. The eval() javascript function fixed it all.
Instead of doing:
alert(cellid.cellwidth);
I did:
alert(eval(cellid).cellwidth);
and everything worked.
Thanks for all your time.
Cheers,
Erick P.
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'));
I have the following code:
var formSubmitHandler = function (link, form) {
//e.preventDefault();
var $form = form;
var val = $form.valid();
var action = $(form).data('action');
var entity = $(form).data('entity');
Do I need the line "var $form = form"? Can I just later on do "var val = form.valid(); ?
It's not my code so I am wondering why the developer added the $ before the form and assigned it?
Update:
Thanks for all your replies. If as has been said it's just to indicate that it's a jQuery variable then could I just remove that line by changing the function parameters to (link, $form) ?
$ and jQuery are basically the jQuery instance.
It's good to understand that $( < place something here >) is a jQuery function call and $your_variable_name is just a variable with a dollar.
Some people use $ in their own variables to indicate that it is a jQuery object. With this naming convention, your source code would like this.
var formSubmitHandler = function (link, form) {
var $form = $(form);
var val = $form.valid();
var action = $form.data('action');
var entity = $form.data('entity');
No, you don't have to use the $ sign. It's just an aesthetic choice usually.
In your example code above, the function's argument is named form function (link, form). Inside the function, the new variable being declared has a $ to it so as to distinguish it from the argument variable form.
That is not neccessary. The dollar sign before a variable is most of the times used as an indication it is a JQuery variable. JQuery uses the dollar sign as a shortcut. Using it in a variable name has no extra meaning other than the aesthetic meaning for the developer that it is a JQuery object.
It has become best practice to use the $ sign to help you distinguish between Javascript variables representing regular DOM elements (and every other data type) and variables that hold a reference to a jQuery object. For the latter you use the $ sign.
I am using the following function closure in a jqgrid (a jquery grid) to retain changes in edits when paging in a variable called 'retainedChanges'- does this look ok; Im i breaking any good practices in javascript;
the code works alright just want to make sure I dont introduce features that can break in the future
(function($){
var retainedChanges;
retainedChanges = new Array();
$.retainChangesOnPaging = function(){
var changedCells = $('#grid').jqGrid('getChangedCells');
// loop over changedCells array, removing duplicates if you want to...
return retainedChanges.push(/* this is inside the loop; push current value to array*/);
....
}
$.getRetainedChanges = function(){
return retainedChanges;
}
})(jQuery);
This works fine, although you should probably accept jQuery as an argument:
(function($){
This way, even if the $ symbol is being used for something else outside of your closure, it won't effect your code inside the closure.
2 more things:
1) You should declare and assign you variable together, and use [] instead of new Array().
2) You're missing a $ symbol here: ('#grid').
For a full rundown, look at this:
(function($){
var retainedChanges = [];
$.retainChangesOnPaging = function(){
var changedCells = $('#grid').jqGrid('getChangedCells');
// loop over changedCells array, removing duplicates if you want to...
return retainedChanges.push(/* this is inside the loop; push current value to array*/);
....
}
$.getRetainedChanges = function(){
return retainedChanges;
}
})(jQuery);
You are passing jQuery into a function that has no arguments and never uses the jQuery object passed in. You may have meant:
(function($){
Other than that it looks fine.
There are several things you could improve:
1) You pass jQuery to the function, but do not use it (you use global object $, if it is defined). Modify your code to accept one parameter, named $:
(function($){
2) You can shorten retainedChanges declaration:
var retainedChanges = new Array();
3) If you are trying to write jQuery plugin, then follow the following tutorial: jQuery: Plugins/Authoring
If not, then maybe use different global object than jQuery?