Accessing a function within a function from outside in javascript - javascript

I have a nested function that I want to call from outside.
var _Config = "";
var tourvar;
function runtour() {
if (_Config.length != 0) {
tourvar = $(function () {
var config = _Config,
autoplay = false,
showtime,
step = 0,
total_steps = config.length;
showControls();
$('#activatetour').live('click', startTour);
function startTour() {
}
function showTooltip() {
}
});
}
}
function proceed() {
tourvar.showTooltip();
}
$(document).ready(function () {
runtour();
});
I was hoping to call it by tourvar.showTooltip(); but I seem to be wrong :) How can I make showTooltip() available from outside the function?

since my previous answer was really a hot headed one, I decided to delete it and provide you with another one:
var _Config = "";
var tourvar;
// Module pattern
(function() {
// private variables
var _config, autoplay, showtime, step, total_steps;
var startTour = function() { };
var showTooltip = function() { };
// Tour object constructor
function Tour(config) {
_config = config;
autoplay = false;
step = 0;
total_steps = _config.length;
// Provide the user with the object methods
this.startTour = startTour;
this.showTooltip = showTooltip;
}
// now you create your tour
if (_Config.length != 0) {
tourvar = new Tour(_Config);
}
})();
function proceed() {
tourvar.showTooltip();
}
$(document).ready(function () {
runtour();
});

function outerFunction() {
window.mynestedfunction = function() {
}
}
mynestedfunction();

Related

How to access the global variables from the requirejs module?

I defined a module (for the code easy to read,I delete some unnecessary line..)
Here is my game.js
define(['util'], function (util) {
return {
createNew : function (setting) {
var game = {
intervalTrigger : function () {
return window.setInterval(function () {
score++;//how to read deal with this value?
}, 1000);
}
}
};
return game;
}
};
});
and use it in app.js:
require.config({
baseUrl: "./src",
});
requirejs(['util', 'game'],
function (util,game) {
var score = 0;
function startgame(level) {
var setting = {};
var g = game.createNew();
g.intervalTrigger();
}
startgame(0);
});
in my case, I need to createNew for few times, so the score can't be stored in the module.
so how to access score in the module game?
You need to define score as an actual module. For example:
define([], function() {
var gameStats = {
score: 0
};
return gameStats;
});
Now you just need to inject wherever you need to work with game stats.
create a get/set function and expose it in the game.js:
define(['util'], function (util) {
var score = 0;
return {
createNew : function (setting) {
var game = {
intervalTrigger : function () {
return window.setInterval(function () {
score++;//how to read deal with this value?
}, 1000);
}
getScore: function(){ return score;} //getting the score
setScore: function(value){score = value;} //setting the score
}
};
return game;
}
};
});
now here you can use:
require.config({
baseUrl: "./src",
});
requirejs(['util', 'game'],
function (util,game) {
var score = 0;
function startgame(level) {
var setting = {};
var g = game.createNew();
g.setScore(score); //setting the score
g.intervalTrigger();
}
startgame(0);
});

Is it possible to unit-test this javascript structure?

Given the following JavaScript structure:
addClickEvent: function() {
element.addEventListener('click', function() {
self.a();
self.b();
});
},
Is it possible to assert that a() and b() have been called without refactoring out the anonymous function or editing it's contents?
Assuming the self in your code is the window.self property.
You could do something like this:
function element_onclick_callsAandB() {
// Arrange
var aCalled = false;
var bCalled = false;
var element = ...;
var origA = self.a;
var origB = self.b;
self.a = function() {
aCalled = true;
origA();
};
self.b = function() {
bCalled = true;
origB();
};
try {
// Act
element.click();
// Assert
assertTrue(aCalled);
assertTrue(bCalled);
}
finally {
self.a = origA;
self.b = origB;
}
}

jquery object - function undefined error

In the following function, my objects inside floatShareBar function is undefined. Do I have to init or define a var before the functions? it throws me js error : .float - function undefined.
(function($) {
.
.
.
$("body").on("ab.snap", function(event) {
if (event.snapPoint >= 768) {
floatShareBar.float()
} else {
floatShareBar.unfloat();
}
});
var floatShareBar = function() {
var fShareBar = $('#article-share');
this.float = function() {
console.log(
};
this.unfloat = function() {
console.log("unfloat");
};
};
.
.
.
})(jQuery);
You need to get an instance of that function with a self instantiating call:
var floatShareBar = (function() {
var fShareBar = $('#article-share');
this.float = function() {
console.log('float');
};
this.unfloat = function() {
console.log("unfloat");
};
return this;
})();
UPDATE 1: I modified it to create an object within the function to attach those functions to, since in the previous example this refers to the window object
var floatShareBar = (function() {
var fShareBar = $('#article-share');
var instance = {};
instance.float = function() {
console.log('float');
};
instance.unfloat = function() {
console.log("unfloat");
};
return instance;
})();
UPDATE 2: You can actually just use the new keyword as well, look here for more info
var floatShareBar = new (function() {
var fShareBar = $('#article-share');
this.float = function() {
console.log('float');
};
this.unfloat = function() {
console.log("unfloat");
};
})();
Change you function to this:
$("body").on("ab.snap", function(event) {
if (event.snapPoint >= 768) {
(new floatShareBar()).float()
} else {
(new floatShareBar()).unfloat();
}
});
function floatShareBar () {
var fShareBar = $('#article-share');
this.float = function() {
console.log(
};
this.unfloat = function() {
console.log("unfloat");
};
};
you should declare functions when using var before you call them.

Javascript callback managment

I'm having trouble with designing a class which exposes its actions through callbacks. Yes my approach works for me but also seems too complex.
To illustrate the problem I've drawn the following picture. I hope it is useful for you to understand the class/model.
In my approach, I use some arrays holding user defined callback functions.
....
rocket.prototype.on = function(eventName, userFunction) {
this.callbacks[eventName].push(userFunction);
}
rocket.prototype.beforeLunch = function(){
userFunctions = this.callbacks['beforeLunch']
for(var i in userFunctions)
userFunctions[i](); // calling the user function
}
rocket.prototype.lunch = function() {
this.beforeLunch();
...
}
....
var myRocket = new Rocket();
myRocket.on('beforeLunch', function() {
// do some work
console.log('the newspaper guys are taking pictures of the rocket');
});
myRocket.on('beforeLunch', function() {
// do some work
console.log('some engineers are making last checks ');
});
I'm wondering what the most used approach is. I guess I could use promises or other libraries to make this implementation more understandable. In this slide using callbacks is considered evil. http://www.slideshare.net/TrevorBurnham/sane-async-patterns
So, should I use a library such as promise or continue and enhance my approach?
var Rocket = function () {
this.timer = null;
this.velocity = 200;
this.heightMoon = 5000;
this.goingToMoon = true;
this.rocketStatus = {
velocity: null,
height: 0,
status: null
};
this.listener = {
};
}
Rocket.prototype.report = function () {
for (var i in this.rocketStatus) {
console.log(this.rocketStatus[i]);
};
};
Rocket.prototype.on = function (name,cb) {
if (this.listener[name]){
this.listener[name].push(cb);
}else{
this.listener[name] = new Array(cb);
}
};
Rocket.prototype.initListener = function (name) {
if (this.listener[name]) {
for (var i = 0; i < this.listener[name].length; i++) {
this.listener[name][i]();
}
return true;
}else{
return false;
};
}
Rocket.prototype.launch = function () {
this.initListener("beforeLaunch");
this.rocketStatus.status = "Launching";
this.move();
this.initListener("afterLaunch");
}
Rocket.prototype.move = function () {
var that = this;
that.initListener("beforeMove");
if (that.goingToMoon) {
that.rocketStatus.height += that.velocity;
}else{
that.rocketStatus.height -= that.velocity;
};
that.rocketStatus.velocity = that.velocity;
if (that.velocity != 0) {
that.rocketStatus.status = "moving";
}else{
that.rocketStatus.status = "not moving";
};
if (that.velocity >= 600){
that.crash();
return;
}
if (that.rocketStatus.height == 2000 && that.goingToMoon)
that.leaveModules();
if (that.rocketStatus.height == that.heightMoon)
that.landToMoon();
if (that.rocketStatus.height == 0 && !that.goingToMoon){
that.landToEarth();
return;
}
that.report();
that.initListener("afterMove");
that.timer = setTimeout(function () {
that.move();
},1000)
}
Rocket.prototype.stop = function () {
clearTimeout(this.timer);
this.initListener("beforeStop");
this.velocity = 0;
this.rocketStatus.status = "Stopped";
console.log(this.rocketStatus.status)
this.initListener("afterStop");
return true;
}
Rocket.prototype.crash = function () {
this.initListener("beforeCrash");
this.rocketStatus.status = "Crashed!";
this.report();
this.stop();
this.initListener("afterCrash");
}
Rocket.prototype.leaveModules = function () {
this.initListener("beforeModules");
this.rocketStatus.status = "Leaving Modules";
this.initListener("afterModules");
}
Rocket.prototype.landToMoon = function () {
this.initListener("beforeLandToMoon");
this.rocketStatus.status = "Landing to Moon";
this.goingToMoon = false;
this.initListener("afterLandToMoon");
}
Rocket.prototype.landToEarth = function () {
this.initListener("beforeLandToEarth");
this.stop();
this.rocketStatus.status = "Landing to Earth";
this.initListener("afterLandToEarth");
}
Rocket.prototype.relaunch = function () {
this.initListener("beforeRelaunch");
this.timer = null;
this.velocity = 200;
this.heightMoon = 5000;
this.goingToMoon = true;
this.rocketStatus = {
velocity: 200,
height: 0,
status: "relaunch"
};
this.launch();
this.initListener("afterRelaunch");
}
init;
var rocket = new Rocket();
rocket.on("afterLaunch", function () {console.log("launch1")})
rocket.on("afterLandToMoon", function () {console.log("land1")})
rocket.on("beforeLandToEarth", function () {console.log("land2")})
rocket.on("afterMove", function () {console.log("move1")})
rocket.on("beforeLaunch", function () {console.log("launch2")})
rocket.launch();
You can add any function before or after any event.
This is my solution for this kinda problem. I am not using any special methods anything. I was just wonder is there any good practise for this like problems. I dig some promise,deferred but i just can't able to to this. Any ideas ?

Can't get two functions to initialize each other

function funcA() {
var fB;
function init() {
fB = new funcB(false); //error here
}
init();
}
function funcB(usefuncA) {
var fA;
function init() {
if (usefuncA) fA = new funcA();
}
init();
}
$(function() {
var test = new funcB(true);
});
I know how to get around this problem in C++, but no idea what tricks there are to fix it in javascript. There is a way, though, right? I absolutely must have each function in the other, and the only other alternative I can think of is putting the contents of funcB in its own .js file then using PHP to create two versions of funcB, one for funcA to use and one in current place of funcB. But that's ridiculous...
This code (your original code, minus the unneeded call to jquery) works fine for me. There's no error.
You can run it here (take a look at the console).
function funcA() {
var fB;
function init() {
fB = new funcB(false); //error here
}
init();
}
function funcB(usefuncA) {
var fA;
function init() {
if (usefuncA) fA = new funcA();
}
init();
}
var test;
test = new funcA();
console.log(test);
test = new funcB();
console.log(test);
test = new funcB(true);
console.log(test);
​
You need to avoid the infinite loop.
function funcA(B) {
var fB;
var that = this;
function init() {
fB = B || new funcB(that);
}
init();
}
function funcB(A) {
var fA;
var that = this;
function init() {
fA = A || new funcA(that);
}
init();
}
$(function() {
var test = new funcB();
});​
(function (testFuncA, $, undefined) {
testFuncA.init = function(caller) { // do stuff },
} (window.testFuncA= window.testFuncA|| {}, jQuery));
(function (testFuncB, $, undefined) {
testFuncB.init = function() { testFuncA.init(this); },
} (window.testFuncB= window.testFuncB|| {}, jQuery));
Do you mean something like this?
function funcA() {
var fB;
this.init = function() {
fB = new funcB(false); //error here
}
}
function funcB(usefuncA) {
var fA;
this.init = function init(usefuncA) {
if (usefuncA) fA = new funcA();
}
}
$(function() {
var test = new funcB();
test.init(true);
});
Is it maybe this what you are looking for?
FuncA = function () {
var fB; this.init(); };
FuncA.prototype.init = function () {
this.fB = new FuncB(false); };
FuncB = function (usefuncA) {
var fA; this.init(usefuncA); };
FuncB.prototype.init = function (usefuncA) {
var fA; if (usefuncA) { this.fA = new FuncA(); } };
var test = new FuncB(true);

Categories

Resources