I have a function which is return a object. in the object i have two function to show the popup and close it. it works within the parent function, but it's not from out side.. is it not a right way to call that.. else how can i call the obj function from out side?
my function :
var popupHandler = function(handler,msg,popUp){
msg = msg == "help" ? "help" : "results"
$(handler).click(function(){
popObj.showPop(); //works
})
$('.cls-how2play').click(function(){
if(msg == 'help') popObj.closePop(); //works
});
var popObj = {
showPop : function(){
if(!(popUp).is(':visible')) $(popUp).fadeIn().children().find('.'+msg).show().siblings().hide();
},
closePop : function(){
$(popUp).fadeOut()
}
}
return popObj;
}
from calling ouside like this :
$('.ui-footer').click( function(){
var closeIt = popupHandler();
closeIt.popObj.closePop() }) //not works.. why?
}
any one can help me the right way to call the obj functions from outside of the returning function?
thanks.
Rather than
closeIt.popObj.closePop()
You want
closeIt.closePop()
Your popupHandler function returns the popObj object, which has the showPop and closePop functions on it. So closeIt is a reference to that same object.
As you are returning the popObj, your closeId will get only the two functions, not wrapped in the popObj object. Therefor you will call the function like so, without popObj:
closeIt.closePop();
There is no need to wrap this in an object since you immediately return it.
you can write
return{
showPop : function(){
if(!(popUp).is(':visible')) $(popUp).fadeIn().children().find('.'+msg).show().siblings().hide();
},
closePop : function(){
$(popUp).fadeOut()
}
}
Now closeIt.closePop(); should work very well.
As i can c
popupHandler is a function, and popObj is a return result of the function "popupHandler"
when the program run to
var closeIt = popupHandler();
it means that the "closeIt" assigned by the result of the function "popupHandler", a obj as the same as the "popObj".
you can consider that "closeIt" is a copy of "popObj".
and "popObj" is not a property of "closeIt" , them are the same.
so you should code closeIt.closePop(), but not closeIt.popObj.closePop(),
and not popObj.closePop() as well.
because popObj was "var"ed in the declare of the popupHandler, it belonged that scope.
You should just call:
closeIt.closePop();
Related
I am writing QUnit test case for my application . Basically I have three Files
like below . DataServices.js has getObjectDetails method which does ajax call
to get data and passes result in callback .
Resolver.js loads DataServices.js using require.
I am writing test case for Proxy.resolve method , in which i want to avoid actual api call , to do this I created mock object of DataServices in Test.js and call Resolver proxy resolve method .
I tried using bind , But still points to actual method of DataServices.js not what I bind in Test.js
DataServices.js
define(["module"], function(module) {
"use strict";
var Details = {
getObjectDetails :function(param,callback){
//API AJAX CALL
// Callback once done
}
};
return {Details : Details }
});
Resolver.js
define(["DataServices"],function(DataServices){
var Proxy= {
resolve : function(){
var Details = DataServices.Details ;
Details.getObjectDetails("xyz", function(result){
// Do Operation After Result
});
}
};
return {Proxy:Proxy}
});
Test.js
define(["Resolver.js" ],function(Resolver){
var DataServices= {
Details : {
getObjectDetails : function(undefined,onSuccess, onError) {
return onSuccess({"X":"Y"});
}
}
};
Resolver.Proxy.resolve.bind(DataServices);
Resolver.Proxy.resolve(); // This is still calling DataServices.js Details
// Not the above muck object
});
In simple program , I want to call mock z function , not z which is inside x .
How to achieve this.
var x = {
z:function(b){
console.log("Z Actual Function..."+b);
},
a : function(){
this.z(3);
}
};
var z = function(b){
console.log("Mock ..."+b)
}
x.a.bind(z);
x.a();
//Z Actual Function...3
But I want Mock ...3 to print
First problem
Using .bind creates a new function, it doesn't change the value of this in the original function.
To use bind in your case you would do something like this instead:
var mockedA = x.a.bind(z);
mockedA();
If you want to call the function immediately without assigning it to a variable you can use .call or .apply instead.
eg:
x.a.call(z); // runs `a()` immediately with `this` set to `z`
The second problem
By binding x.a to z you're changing the value of this to the value provided (the mock z function). So inside x.a when you call this.z(3) you're effectively trying to call z.z(3), which is a non existent function and so will throw a TypeError.
There are probably better ways of doing it but this is a way that answers your question:
var x = {
z:function(b){
console.log("Z Actual Function..."+b);
},
a : function(){
this.z(3);
}
};
var mock = {};
mock.z = function(b){
console.log("Mock ..."+b)
}
// with bind
var mockXA = x.a.bind(mock);
mockXA();
// with call
//x.a.call(mock)
var fbToggle = document.getElementById("fbToggle");
and later in the script
fbToggle.addEventListener("click", toggle("fbContainer"));
Console tells me that fbToggle is NULL
This is in the document though.
<input type="checkbox" id="fbToggle">
I wasnt using eventListener before, so maybe there is a special order of declaration i'm missing ?
EDIT :
entire js :
function toggle(target) {
var obj = document.getElementById(target);
display = obj.style.display;
if (display == "none") {display = "block"}
else {display = "none"}
}
function init() {
var fbToggle = document.getElementById("fbToggle");
var twitToggle = document.getElementById("twitToggle");
var pinToggle = document.getElementById("pinToggle");
console.log(fbToggle); // NULL
fbToggle.addEventListener("click", toggle("fbContainer"));
twitToggle.addEventListener("click", toggle("twitContainer"));
pinToggle.addEventListener("click", toggle("pinContainer"));
}
window.onload = init();
HTML is way too long.but JS is in head, called from external file. Also i'm not in quirk mode.
It is not clear where "later in the script" is. If it is in different scope definitely it is not going to work. Suggesting you to keep everything in a global object if possible so that you can access from different places in the script.
window.globals = {};
window.globals.fbToggle = document.getElementById("fbToggle");
window.globals.fbToggle.addEventListener("click", function () {
toggle("fbContainer")
});
function toggle(container) {
alert(container);
}
http://jsfiddle.net/ST938/
Another point is addEventListener expects a function or function idenitifier, NOT a function call.
addEventListener("click", toggle("fbContainer")); // wrong
addEventListener("click", toggle); // correct
So if you want to pass a parameter
window.globals.fbToggle.addEventListener("click", function () {
toggle("fbContainer")
});
function toggle(container) {
alert(container);
}
In JavaScript, putting brackets after a function name causes it to be called. If you want to reference a function without calling it you must not put brackets after the name:
window.onload = init(); // this calls init() immediately
window.onload = init; // this correctly stores init in window.onload
The same applies to toggle(). If you need to pre-specify some of the arguments you can wrap it in an anonymous function:
fbToggle.addEventListener("click", function() { toggle("fbContainer"); });
or you can use bind:
fbToggle.addEventListener("click", toggle.bind(null, "fbContainer"));
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);
});
I want to pass the "passedThisValue" to my "start_battle" function and use the "start_battle" function in my "Rematch". But the modal just hangs why is this happening? what could be wrong? Please help! :) Thank you.
CODE:
function start_battle(){
$.ajax({
data: {
receivePassedValue: passedThisValue
},
success: function(data){
}
});
}
$("#start_battle").click(function() {
$.ajax({
success: function(data){
var toAppend = '';
if(typeof data === "object"){
var passedThisValue = '';
for(var i=0;i<data.length;i++){
passedThisValue = data[i]['thisValue'];
}
start_battle(); // can I still get the passedThisValue?
}
}
});
$("#battle").dialog({
modal:true,
buttons: {
"Rematch": function(){
start_battle(); // can I still get the passedThisValue?
}
}
});
$("#battle").show(500);
});
When you call a function, you don't use function start_battle();, you just use start_battle();.
When you pass a value to a function, you need to use this syntax: start_battle(param1, param2);.
When you want to get a value from a function, you need to return it in the function, like so:
function start_battle(param1) {
// Do something
return param1;
}
When you want to store a returned value from a function, you do something like: var returned = start_battle(param1);
And the fact that you don't know why the modal just hangs, means that you didn't check the browser's error console, which can hold some pretty important information on what's wrong. Try checking that and posting here so we can see the current problem
Your function declaration seems a little off. I think you should leave off the $ from function. Just do this
function start_battle() {
Also, when you're calling a function, you don't say function before it. And if you want to pass a value to the function, you have to put it inside the parenthesis, both when defining the function and when calling it. Like this
function start_battle(someValue) {
// do some stuff with someValue
}
// inside your .click, call start_battle like this
start_battle(passedThisValue);
Pretty basic stuff. But either one of those problems could be causing the hang, which was likely a javascript error.
I can't seem to get back on track with this one. I simply put a function in a variable and want to call it later, providing it with a parameter:
var logic = function(itemId) {
console.log(itemId);
};
jQuery("#flipright").click(function() { logic.apply(1); } );
This prints "undefinded".
What am I missing?
Simply call logic(1).
If you want to pass a context, you can use call or apply :
logic.apply(context, [1]);
// or
logic.call(context, 1);
You should use apply or call if you want to pass a context to another function - meaning that the this keyword in the called function will refer to whatever context you are passing to it.
Here's a scenario :
var logic = function(itemId) {
console.log(this,itemId);
};
jQuery("#flipright").click(function() {
// output to console the current jquery object and "1"
logic.call(this,1);
});
Make it:
jQuery("#flipright").click(function() { logic(1); } );
ref for apply: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply