Use value from method in javascript object to use in setTimeout function - javascript

I have tried different things but I do seem to be looking something over that is too obvious. Trying to use the value a function(method) returns inside an object and use it in another method with setTimeout within that same object.
This is the html:
<h1>3000</h1>
The javascript (jQuery in this case):
var foo = {
getValue: function() {
var h1Text = $('h1').text();
h1Text = parseInt(h1Text);
return h1Text;
},
useValue: function() {
var time = this.getValue();
var alertIt = alert('Hello');
setTimeout(alertIt,time);
}
};
foo.useValue();
// log shows correct value
console.log(foo.getValue());
// returns a number
console.log(typeof(foo.getValue()));
The alert does show up, but on load rather than using those 3 seconds.
It does log the correct value and also says it's a number so I'm really not sure what I am doing wrong. Any help is appreciated. Thanks

In useValue() you call alert('Hello'), so it's executed immediately and the result is stored in alertIt variable. You should put it inside the function like this, as setTimeout expects a function as a first parameter:
var alertIt = function() {
alert('Hello');
}
setTimeout(alertIt,time);

setTiimeout expects function and not variable.
Also var alertIt = alert('Hello'); this will return undefined.
Note: var a = function() will call it and assign return value. To assign a function to a variable with parameter, use .bind
Try alert.bind(null, "hello");
For demo purpose, I have hardcoded value of delay and commented getValue code.
var foo = {
getValue: function() {
//var h1Text = $('h1').text();
//h1Text = parseInt(h1Text);
return true// h1Text;
},
useValue: function() {
var time = 3000//this.getValue();
var alertIt = alert.bind(null,'Hello');
setTimeout(alertIt, time);
}
};
foo.useValue();
// log shows correct value
console.log(foo.getValue());
// returns a number
console.log(typeof(foo.getValue()));

Related

Is it possible to repeat function exclude one method

var myfunction = function(){
$('.menu').delay(3000).slideDown("fast").attr('style', 'color:#fff')
return false;
});
Can i repeat myfunction exclude delay(3000)?
Means something like $('#submit').click(myfunction); but myfunction should exclude .delay(3000)
Set your function up with a variable for time:
var myfunction = function(delayTime) {
$('.menu').delay(delayTime).slideDown("fast").attr('style', 'color:#fff')
return false;
});
Then call it with the time value as an argument:
myfunction(3000);
or
myfunction(0);
In cases like this, I like to create a curried function (that is, a function that returns a function).
function myFunction(doDelay){
return function(){
$('.menu').delay(doDelay ? 3000 : 0).slideDown('fast') //...
return false
}
}
Then you could set up your click listener like
$('#submit').click(myFunction(false))
And call it with the delay like myFunction(true)(), or create different delayed instances like var myFunctionDelayed = myFunction(true) or var myFunctionNoDelay = myFunction(false)

return a variable from .click() javascript function

First of all excuse for my weak english, I try to use the following javascript code and I want to return id variable and use it in other function, but it seem does not work correctly and does not return it, can someone help me out writting this
var idcb = $('.box').click(function() {
var id = $(this).attr('id');
return id;
});
I want to use var idcb in this function :
$(".hs").click(function() {
$(idhs).slideToggle("slow");
return false;
});
});
for that to work, the jquery click implementation would need to know that the function you pass it returns a value, and that it itself should return that value - which isn't the case.
instead, you could use some closure magic to do this easily. try this:
var idcb;
$('.box').click(function() {
idcb = $(this).attr('id');
});
You are passing an anonymous function to an event handler, you cannot return a value from this type of function. The solution is to use closures to get around this :
var idcb = null;
$('.box').click(function() {
idcb = $(this).attr('id');
});
The variable idcb will always be set to the id of the last .box that was clicked.
The function is given as a parameter to the click function and is run asynchronously when the user clicks on an element. So you can't return a value directly, since the function won't be run immediately. You can look up the id value another way, or pass it to a function to work with instead of returning it, or just do this:
var idcb = $('.box').click(function() {
var id = $(this).attr('id');
$(id).slideToggle("slow");
});
You cannot do it the way you are trying to. However, what you can do is use a variable that is accessible by both functions to share values between them.
var icdb = 'test';
function a() {
icdb = 'another value';
}
function b() {
console.log(icdb);
}
a();
b();
You could also call b from a and pass the variable as argument:
function a() {
b('test');
}
function b(icdb) {
console.log(icdb);
}
a();
your variable idcb contains the click handler !
you need to declare the vriable outside the handler and assign to it inside to make this work:
var idcb = null;
// ... whatever
$('.box').click(function() {
idcb = $(this).attr('id');
return true; // return 'true' from an event handler to indicate successful completion
});
Check this out
var id=null;
$('.box').click(function() {
id = $(this).attr("id");
});
$(".hs").click(function() {
$("#"+id).slideToggle("slow");
return false;
});
You could pass in the an object as a reference to the click function
and change the value from the callback. Another option is using closures
The caveat to this jsfiddle is that you have to call a .box element first.
http://jsfiddle.net/D6B73/2/
var idcb = {};
$('.box').click(idcb, function (event) {
event.data.value = $(this).attr('id');
console.log(idcb.value);
});
$('.hs').click(function() {
$('#'+idbc.value).slideToggle("slow");
});
You can do it this way:
$(".hs").on('click', function() {
var id = $('.box').attr('id');
alert(id);
});

cannot access function within function in javascript

I need to know what I am doing wrong because I cannot call the internal functions show or hide?
(function()
{
var Fresh = {
notify:function()
{
var timeout = 20000;
$("#notify-container div").get(0).id.substr(7,1) == "1" && (show(),setTimeout(hide(),timeout));
var show = function ()
{
$("body").animate({marginTop: "2.5em"}, "fast", "linear");
$("#notify-container div:eq(0)").fadeIn("slow");
},
hide = function()
{
$("#notify-container div").hide();
}
}//END notify
}
window.Fresh = Fresh;
})();
Fresh.notify();
thanks, Richard
UPDATE
If you wanted to be able to do something like: Fresh.notify.showMessage(), all you need to do is assign a property to the function notify:
var Fresh = {notify:function(){return 'notify called';}};
Fresh.notify.showMessage = function () { return this() + ' and showMessage, too!';};
Fresh.notify();//notify called
Fresh.notify.showMessage();//notify called and showMessage, too!
This will point to the function object here, and can be called as such (this() === Fresh.notify();). That's all there is too it.
There's a number of issues with this code. First of all: it's great that you're trying to use closures. But you're not using them to the fullest, if you don't mind my saying. For example: the notify method is packed with function declarations and jQuery selectors. This means that each time the method is invoked, new function objects will be created and the selectors will cause the dom to be searched time and time again. It's better to just keep the functions and the dom elements referenced in the closure scope:
(function()
{
var body = $("body");
var notifyDiv = $("#notify-container div")[0];
var notifyDivEq0 = $("#notify-container div:eq(0)");
var show = function ()
{
body.animate({marginTop: "2.5em"}, "fast", "linear");
notifyDivEq0.fadeIn("slow");
};
var hide = function()
{//notifyDiv is not a jQ object, just pass it to jQ again:
$(notifyDiv).hide();
};
var timeout = 20000;
var Fresh = {
notify:function()
{
//this doesn't really make sense to me...
//notifyDiv.id.substr(7,1) == "1" && (show(),setTimeout(hide,timeout));
//I think this is what you want:
if (notifyDiv.id.charAt(6) === '1')
{
show();
setTimeout(hide,timeout);//pass function reference
//setTimeout(hide(),timeout); calls return value of hide, which is undefined here
}
}//END notify
}
window.Fresh = Fresh;
})();
Fresh.notify();
It's hard to make suggestions in this case, though because, on its own, this code doesn't really make much sense. I'd suggest you set up a fiddle so we can see the code at work (or see the code fail :P)
First, you're trying to use show value when it's not defined yet (though show variable does exist in that scope):
function test() {
show(); // TypeError: show is not a function
var show = function() { console.log(42); };
}
It's easily fixable with moving var show line above the point where it'll be called:
function test() {
var show = function() { console.log(42); };
show();
}
test(); // 42
... or if you define functions in more 'traditional' way (with function show() { ... } notation).
function test() {
show();
function show() { console.log(42); };
}
test(); // 42
Second, you should use this instead:
... && (show(), setTimeout(hide, timeout) );
... as it's the function name, and not the function result, that should be passed to setTimeout as the first argument.
You have to define show and hide before, also change the hide() as they said.
The result will be something like this:
(function()
{
var Fresh = {
notify:function()
{
var show = function()
{
$("body").animate({marginTop: "2.5em"}, "fast", "linear");
$("#notify-container div:eq(0)").fadeIn("slow");
},
hide = function()
{
$("#notify-container div").hide();
},
timeout = 20000;
$("#notify-container div").get(0).id.substr(7,1) == "1" && ( show(), setTimeout(hide,timeout) );
}//END notify
}
window.Fresh = Fresh;
})();
Fresh.notify();
I think order of calling show , hide is the matter . I have modified your code . It works fine . Please visit the link
http://jsfiddle.net/dzZe3/1/
the
(show(),setTimeout(hide(),timeout));
needs to at least be
(show(),setTimeout(function() {hide()},timeout));
or
(show(),setTimeout(hide,timeout));

how to set to call a function from the current object using settimer

function Something() {
this.var1 = 0;
this.var2 = 2;
this.mytimer;
this.getCars=function() {
//some code
};
this.start = function(l) {
this.updateTimer=setInterval("this.getCars();" , 5000);
};
}
var smth = new Something();
smth.start();
When I type in this.getCars() it does not work. if the function is global declared and i put in for example just getCars it works.
I don't know how to work out this problem because setInterval becomes as parameter a String.
Can somebody help me put with this?
var me = this
setInterval(function() {me.getCars()}, 5000)
if you happen to be using prototype, you could also use the handy bind method:
setInterval(this.getCars.bind(this), 5000)
Try this:
function Something() {
this.var1 = 0;
this.var2 = 2;
this.mytimer;
var me = this;
this.getCars = function() {
console.log(me.var2);
};
this.start = function(l) {
me.updateTimer = setInterval(me.getCars, 1000);
}
}
var smth = new Something();
smth.start();
The console.log() bit is Firefox/Firebug. Replace it with something else if you're not using that (although I would highly recommend developing with it).
Basically the problem is that when you call a function, even a method of an object, the way you call it determines the value of this. See Method binding for more details. So what you do is fix the value of this as I've done in the above example (for methods).

jQuery binding function on focus

I'm writing a little plugin for jQuery and so far I've got this:
(function($){
$.fn.extend({
someFunction: function() {
return this.each(function() {
var obj = $(this);
obj.focus(someInternalFunction(obj));
});
}
});
function someInternalFunction(obj) {
};
})(jQuery);
The problem is, when i attach someFunction to the object, the object gets focus and binding of someInternalFunction on focus event fails.
Then I tried to bind function to wrap the function call in the other function:
obj.focus(function() {
someInternalFunction($(this));
});
This code works, but it isn't pretty at all. Is it possible to bind function on focus without wrapping it in the other function?
$.fn.bindFocus() = function(){
var internalFunction = function(){
var $this = $(this),
self = this;
// try do stuff here
};
return this.each(function(){
$(this).bind('focus', internalFunction);
});
}
$('#myElement').bindFocus();
Hope it'll help ?
EDT. Sorry, first time get you wrong :)
Here:
obj.focus(someInternalFunction(obj));
^^^^^
... you're calling the function, meaning that its return value is the thing that actually ends up being passed to focus(). Instead you want to pass a function to focus(). Given the fact that you want to pass obj to someInternalFunction, you'll have to define an additional function to wrap it all:
obj.focus(function(){
someInternalFunction(obj);
});
Just to make things clear:
var x = function() { return 3; }; // Defining a function
x; // -> this is a function reference
x(); // -> this is 3

Categories

Resources