Javascript - Add Variables in Jquery Command - javascript

function bookRemoved(bookId)
{
alert(bookId) ;
$(document).ready(function() {
$('.className').hide(1000); // Want it Here
} );}
In Above example, the bookId returns class Name. How can I use it as class name to hide it as shown in above example.
I would like something like this:
$('.bookId').hide(1000); // Want it Here
bookId should return its value. Suppose if bookId has 23, it should look like this.
$('.23').hide(1000); // Want it Here
PS: I am new to Javascript and Jquery

Try like
function bookRemoved(bookId)
{
alert(bookId) ;
$('.' + bookId).hide(1000); // Want it Here
}
We dont need DOM ready there,in the defined function.

What you are looking for is a means of passing the argument of one function as argument to another. Variables can be passed into functions, $ is just a function, within the (...) sequence following a function reference.
function bookRemoved(bookId) {
alert(bookId);
$(document).ready(function() {
$('.'+bookId).hide(1000);
});
};
In this case:
the function alert is fired on the variable bookId
the function $ is fired on the document variable.
the method ready is accessed from the returned object of $(document)
ready is fired with a function, an anonymous function (i.e., without a name)
the function $ is fired on a string concatenation between . and bookId
the hide method is then accessed and fired with 1000
Hopefully this better explains the general terminology and what it is that is occurring within the function definition.

function bookRemoved(bookId) {
alert(bookId);
$(document).ready(function () {
$('.' + bookId).hide(1000);
});
}
Do you mean this?

$('.' + bookId).hide(1000);
In javascript + operator is used to...
add nembers.
concatenate strings if one of the operand is string.
for example...
1 + 2 == 3
"abc" + "xyz" == "abcxyz" and
"1" + 2 == "12" // "1" here is a string

Cleaner approach. Seperate your document.ready function.
$(document).ready(function() {
function bookRemoved(bookId) {
$(bookId).hide(1000);
}
//pass in your specified class name OR id as the argument.
bookRemoved('.someClasssName');
});
More info on hide method here: http://api.jquery.com/hide/

Related

JavaScript: call-by-name parameter evaluation

I wrote a function, which reports that some element was loaded:
var reportLoaded = function(element) {
$("<div>" + element + " loaded " + new Date().getMilliseconds()
+ "</div>").appendTo("body");
}
But when I attach this function to, for example, jQuery's ready method:
$(document).ready(reportLoaded("document"))
it's not working, because function is evaluated directly.
So I had to do something like this:
var reportLoadedDelayed = function(element) {
return function() {
reportLoaded(element);
}
}
$(document).ready(reportLoadedDelayed("document"))
Is there a short notation to specify that you want your parameters evaluated by name? Like in Scala you can declare a function:
def lazyEval(x: => Int) = {println("lazy"); x;}
and the x will be evaluated when it's actually needed, if at all.
But when I attach this function to, for example, jQuery's ready method:
$(document).ready(reportLoaded("document"))
That doesn't attach it to ready. It calls reportLoaded("document") and passes its return value into ready, exactly the way foo(bar()) calls bar and passes its return value into foo.
If you want to actually pass a function reference in, use a function expression or Function#bind, which can be used to curry arguments:
$(document).ready(function() {
reportLoaded("document");
});
or
$(document).ready(reportLoaded.bind(null, "document"));
or actually, jQuery has $.proxy:
$(document).ready($.proxy(reportLoaded, null, "document"));
If you do this a lot, you can get rid of the need to type null all the time by giving yourself a curry function:
// Best to have this in a scoping function
var slice = Array.prototype.slice;
Function.prototype.curry = function() {
var args = slice.call(arguments, 0);
args.unshift(null);
return this.bind.apply(this, args);
};
Note that Function#bind is "new" in ES5 (2009), but easily polyfilled if you need to support older browsers like IE8.
There is no such thing as lambda expressions in Javascript, the closest is a function expression:
$(document).ready(function(){ reportLoaded("document"); });
You can also use the proxy method to create a function from the function identifier, and bind the parameter to it:
$(document).ready($.proxy(reportLoaded, this, "document"));

Getting "This" into a namespace in Javascript

I'm sure this should be a simple question but I'm still learning so here it goes:
I have some code to run a function on click to assign the clicked element's ID to a variable but I don't know how to pass the "this.id" value to the namespace without making a global variable (which I thought was bad).
<script>
fsa = (function() {
function GetTemplateLoc() {
templateId = document.activeElement.id;
alert(templateId + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
//call the functions
$(document).on('click', '.template', function () {
fsa.GetTemplateLoc();
});
</script>
and HTML with random picture:
<img id="template-1" class="template" src="http://fc02.deviantart.net/fs70/f/2010/028/c/b/cb21eda885b4cc6ee3f549a417770596.png"/>
<img id="template-2" class="template" src="http://fc02.deviantart.net/fs70/f/2010/028/c/b/cb21eda885b4cc6ee3f549a417770596.png"/>
The following would work:
var fsa = (function() {
function GetTemplateLoc() {
var templateId = this.id;
alert(templateId);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
//call the functions
$(document).on('click', '.template', fsa.GetTemplateLoc);
jQuery generally calls functions you pass as event handlers with this set to the DOM object the event is associated with.
In this case it will call GetTemplateLoc() with this set to either .template element, so you can use this directly in the function and don't need to pass any parameters.
Important tip: Always declare variables using var. JavaScript has no automatic function-local scope for variables, i.e. every variable declared without var is global, no matter where you declare it. In other words, forgetting var counts as a bug.
Try this : You can directly use this.id to pass id of the clicked element where this refers to the instance of clicked element.
<script>
fsa = (function() {
function GetTemplateLoc(templateId ) {
//templateId = document.activeElement.id;
alert(templateId + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
//call the functions
$(document).on('click', '.template', function () {
fsa.GetTemplateLoc(this.id);
});
</script>
If you're able to use jQuery within the GetTemplateLoc function, you could do something like this:
var fsa = (function() {
function GetTemplateLoc($trigger) {
var templateId = $trigger.attr('id'),
templateId2 = $($trigger.siblings('.template')[0]).attr('id');
alert(templateId + ' ' + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
$(document).on('click', '.template', function () {
fsa.GetTemplateLoc($(this));
});
You can set GetTemplateLoc to expect a jQuery object as a parameter (the dollar sign at the beginning of $trigger can be used to distinguish it as a jQuery object rather than any other data type, it's not necessary but can help clarify things sometimes).
templateId will store the value of the clicked image's ID, and templateId2 will store the value of the other image's ID. I also added a space between the two variables in the alert.
If you can't use jQuery within GetTemplateLoc, you could do something like this:
var fsa = (function() {
function GetTemplateLoc(trigger) {
var templateId = trigger.id;
var templateId2 = trigger.nextElementSibling == null ? trigger.previousElementSibling.id : trigger.nextElementSibling.id;
alert(templateId + ' ' + templateId2);
}
return {
GetTemplateLoc: GetTemplateLoc,
}
})();
This time, the .template that triggered the event is passed into GetTemplateLoc, but this time it's not a jQuery object. templateId is assigned to the trigger's ID and then templateId2 is assigned in a ternary. First, the nextElementSibling of trigger is checked to see if it's null. If it is, we know that trigger is the second of the two .template elements. Therefore we can set templateId2 to the ID of trigger's previous sibling. If trigger's nextElementSibling is not null, then we know that trigger is the first template and we populate templateId2 with the ID of nextElementSibling. This exact method will only work with two .template's, if there are more you'll need some additional/different logic, probably to retrieve all .template IDs and then loop through them to add them to the alert message. Hope this helps.

Send runtime parameter value to the jQuery's ON method?

I have a simple button. and I need to send data to the handler when clicked.
So I have this code using the ON overload method :
.on( events [, data ], handler(eventObject) )
I've created this sample :
var aaa="john";
function greet(event) { alert("Hello "+event.data.name); }
$("button").on("click", { name: aaa}, greet);
setTimeout(function (){aaa="paul"},2000)
But after waiting 2 sec , I still see: "Hello John"
So I assume that the aaa value is bounded at interpretation time.
Question :
How can I change the code so that after 2 seconds it will alert : Hello Paul ?
JSBIN
A simple way is to use an object literal. You can pass it as event data and keep a reference that you modify later:
var greetData = {
name: "john"
};
function greet(event)
{
alert("Hello " + event.data.name);
}
$("button").on("click", greetData, greet);
setTimeout(function() {
greetData.name = "paul";
}, 2000);
You will find an updated JS Bin here.
Frédéric Hamidi's answer is better. Will leave this just as an alternative.
If you change it so that you pass a function that loads the name instead of the name it self it will work:
var aaa="john";
function getName() {
return aaa;
}
function greet(event) { alert("Hello "+event.data.name()); }
$("button").on("click", { name: getName}, greet);
setTimeout(function (){aaa="paul";},2000);
http://jsbin.com/ohAJihi/4/edit
It is a little confusing to understand what are you
trying to achieve. If you are using setTimeout; theres no need to use a button onclick handler.
Secondly, the scope of the setTimeout function is always the window object. So if you need to access the value from your object, please create a reference of it and use in the setTimeout function.

in jaydata: pass variables to filter, only global works

I have this function:
function db_borrarServer(idABorrar){
serversDB.servidores
.filter(function(elementoEncontrado) {
return elementoEncontrado.id_local == this.idABorrar;
})
.forEach(function(elementoEncontrado){
console.log('Starting to remove ' + elementoEncontrado.nombre);
serversDB.servidores.remove(elementoEncontrado);
serversDB.saveChanges();
});
}
does not work, but it does if I replace the variable "this.idABorrar" with a number, it does
return elementoEncontrado.id_local == 3;
or if I declare idABorrar as a global, works to.
I need to pass idABorrar as variable. How can I do this?
The EntitySet filter() function (as any other predicate functions) are not real closure blocks, rather an expression tree written as a function. To resolve variables in this scope you can only rely on the Global and the this which represents the param context. This follows HTML5 Array.filter syntax. To access closure variables you need to pass them via the param. Some examples
inside an event handler, the longest syntax is:
$('#myelement').click(function() {
var element = this;
context.set.filter(function(it) { return it.id_local == this.id; },
{ id: element.id});
});
you can also however omit the this to reference the params as of JayData 1.2 and also use string predicates
$('#myelement').click(function() {
var element = this;
context.set.filter("it.id_local == id", { id: element.id});
});
Note that in the string syntax the use of it to denote the lambda argument is mandatory.
In JayData 1.3 we will have an even simplex calling syntax
$('#myelement').click(function() {
var element = this;
context.set.filter("it.id_local", "==", element.id);
});
In the filter you should pass an object which is the this object, like this:
.filter(function(){},{idABorrar: foo})
foo can be const or any variable which is in scope.
The .filter() function takes an optional 2nd parameter which is assigned to this inside of the first parameter function.
So you can modify your code like so :
function db_borrarServer(idABorrar){
serversDB.servidores
.filter(function(elementoEncontrado) {
return elementoEncontrado.id_local == this;
}, idABorrar)
.forEach(function(elementoEncontrado){
console.log('Starting to remove ' + elementoEncontrado.nombre);
serversDB.servidores.remove(elementoEncontrado);
serversDB.saveChanges();
});
}
Let me know how you go - I'm very new to jaydata too and I've also been going a bit crazy trying to get my head into this paradigm.
But I came across your question trying to solve the same issue, and this is how I resolved it for me.

Is there a way to create a function that can be either a click event or an onload event, depending on the class of the body?

Basically the Title states the question, but the situation is this (it's difficult to replicate with jsbin or anything else, so I'm going to try to solve without doing that).
I have a function that is called on the click of a button. The click event will tell the output what font will be used. However, on certain pages, I want the font to be declared by the class of the body element and not on the click of a button.
I'm running into two problems.
When I try to pass an argument and receive a parameter, the parameter is an event, rather than whatever I want to pass.
If I pass the event as the first parameter and the font I want as the second, I get undefined as my font variable and the function does not work.
Any help on making a function be flexible in this way would help me out a lot.
Edit: Here's a simplified version of what I've got
function fontSelection(font) {
var self = $(this),
inputOne = $('li:eq(0) input').val(),
inputTwo = $('li:eq(1) input').val(),
inputThree = $('li:eq(2) input').val(),
resultOne = $('div:eq(0)'),
resultTwo = $('div:eq(1)'),
resultThree = $('div:eq(2)');
font = font || $('div.font').attr('title').toLowerCase();
resultOne.removeClass().addClass(inputOne + ' someclass ' + font);
resultTwo.removeClass().addClass(inputTwo + ' someclass ' + font);
resultThree.removeClass().addClass(inputThree + ' someclass ' + font);
}
Rather than pass your function directly to the event registration, you pass an anonymous function that then calls your function with the desired arguments.
So, rather than this:
$("#myButton").click(callMyFunction);
You use this which allows you to specify the exact arguments you want:
$("#myButton").click(function(e) {
callMyFunction(myParam1, myParam2);
});
If you want to preserve, the value of this in your function, then you need to use .call() like this to explicitly set it appropriately in your function:
$("#myButton").click(function(e) {
fontSelection.call(this, myParam1, myParam2);
});
Or, just pass it as an argument and use the argument in your function instead of this:
$("#myButton").click(function(e) {
fontSelection(this, myParam1, myParam2);
});
Try this on for size: A function that, if given an argument, sets the font to be used. If the argument is not set, then reads the body tag for a font.
$(function () {
if ($('body').hasClass('your class for onload change')) {
// change font
} else {
$('button').click(your_function);
}
});
Edit:
if you want to use this in your function and want it to reference on body in first case and some another dom element in second case, you can use call or apply
$(function () {
if ($('body').hasClass('your class for onload change')) {
fontSelection.apply($('body').get(0), [font]);
} else {
$('button').click(function () {
fontSelection.apply(this, [font]);
});
}
});

Categories

Resources