how can i access a variable that was intialsed in a function, but the main.name is giving me a null value, i know the value is initliased in the function, or on main, but not in the feed!! this is my example,
var main = Titanium.UI.createWindow();
var feed = Titanium.UI.createWindow({
title:'feeds',
url:'main_windows/feeds.js',
barImage:'bg_content.gif',
username:main.name //im trying too access this varibale from main.
});
Ti.App.addEventListener('grantEntrance',function(event)
{
main.title ='Welcome'+event.username;
main.url = 'main_windows/main.js';
main.name = event.username; // this is where the varibale is intialised
main.email = event.email;
main.barImage='bg_content.gif';
});
sorry if this seems like a stupid question but im a newbie to javascript, so just tell me to delete it. i was wondering if you can turn it into a gloab or something.
You're trying to get variable that is not initialized yet. Since you're assigning main.name in a callback of event it will be initialized only after that event is fired. I'm not sure what's the logic of you'r application, but I guess you're able to initialize window inside this callback:
Ti.App.addEventListener('grantEntrance',function(event) {
main.title ='Welcome'+event.username;
main.url = 'main_windows/main.js';
main.name = event.username;
main.email = event.email;
main.barImage='bg_content.gif';
var feed = Titanium.UI.createWindow({
title:'feeds',
url:'main_windows/feeds.js',
barImage:'bg_content.gif',
username:main.name
});
});
Or, just set username property of the window inside callback:
var feed = Titanium.UI.createWindow({
title:'feeds',
url:'main_windows/feeds.js',
barImage:'bg_content.gif',
});
Ti.App.addEventListener('grantEntrance',function(event) {
main.title ='Welcome'+event.username;
main.url = 'main_windows/main.js';
main.name = event.username;
main.email = event.email;
main.barImage='bg_content.gif';
feed.username = main.name
});
Also, from personal experience: Titanium is not the best way to "fill the power" of js: some of methods are running asynchroniusly, and it causes weird issues. So if you're newbie it could be a pain in the ass..
Anyway good luck :)
Related
newbie Javscripter here. I'm trying to get some practice with modules and I'm hitting a wall. I'm trying to get the controller module to access the wagerAmount(input by user) from the UIControl module with minimal success. My relevant code is as follows:
var UIControl = (function() {
return {
getWager: function() {
return {
wagerAmount: document.getElementById('wager').value
};
}
};
})();
var controller = (function(UICont) {
var topics = ['sports', 'history', 'technology', 'music', 'movies'];
var wager = UICont.getWager();
var changeClass = function() {
document.getElementById('bet').addEventListener('click', function() {
console.log(wager);
for (var i = 0; i < topics.length; i++) {
if (document.getElementById(topics[i]).classList[1] == 'select') {
activateAnswers();
}
}
});
}
})(UIControl);
When I run this, console.log(wager) prints a empty string, {wagerAmount: ""}. If I declare wager inside the changeClass function, the same thing happens. However, if I declare wager inside the click event, it prints the number input by the user. BUT, the topics variable, declared in the controller is being accessed just fine by the click event. The main problem here is when I need to add the functionality to multiple click events, I would have to declare a new variable in each click event to access the same function, which sounds like bad practice. So what's going on here?
Ok, so after spending a couple hours last night trying to figure this out, I quickly figured out the solution this morning after some coffee. In case anyone else has this problem I'll post my solution, and if someone else comes up with something else, they can post as well.
Instead of declaring wager in the controller anywhere, I created a new function inside controller:
var retrieveWager = function() {
return {
wager: UICont.getWager().wagerAmount
};
}
and then could access it in any of the click events like this:
retrieveWager().wager;
I want to add a variable or a function to my mdDialog. Im not to sure on how to create a custom mdDialog, Im new to angularjs.
This is my mdDialog:
vm.dialog_up = function() {
vm.dis = true;
alert = $mdDialog.alert()
.title('Attention, ')
.content('Do you want to edit your Information?')
.ok('Close');
$mdDialog
.show( alert )
.finally(function() {
alert = undefined;
});
}
I want to maybe add a function to the .ok button.
JavaScript is a very liberal language and it allows you to add properties and methods to objects. For example:
var modal = {};
modal.x = 5;//this assigns the value of `5` to the newly attached property `x`
modal.testMethod = function() {
//Do something here
}
PS:
Though personally, I think that modifying framework objects can cause side effects.
<script src="http://domain.com/source1.js"></script>
<script src="http://domain.com/source2.js"></script>
source1.js
var PICTURE_PATH = "";
var PICTURE_ROOT = base_url+"YOUTAILOR_files/";
var PROGRAM = parseInt("1");
source2.js
if(PROGRAM==3 || PROGRAM==4 || PROGRAM==5)
{
}
I could not access value of program in source2.js..
When you declare var source1Var outside a function you are actually creating a variable on the window object. So you should just be able to access it from source2.js. Just make sure source1.js is before source2.js in the script tags...
If however you're declaring it within a function, it will be private to that function. If you really need to you could set it on window explicitly.
In source1.js
function foo() {
window.source1Var = 3;
}
In source2.js
function bar() {
console.log(source1Var); // this will search window if it cannot find in the local scope.
}
What is the problem you're trying to solve? It is generally better to use some form of dependency injection, event listeners, builder pattern etc. rather than using global variables.
do something like in your first .js
var VAR = {
myvalue: "hai"
};
then call it in second like
alert(VAR.myvalue);
It's easier than you think. If variable is global, you should access it from anywhere.
// source1.js
var colorCodes = {
back : "#fff",
front : "#888",
side : "#369"
};
And in another file:
// source2.js
alert (colorCodes.back); // alerts `#fff`
First of all I want to say that I am sorry for not using the Code sample. This is my first time asking on stackoverflow and I found it really confusing.
I have this javascript code which works perfectly, but when I try to duplicate it and change the variable names it doesn't seem to work.
JavaScript
function saveEdits() {
var editElem = document.getElementById("edit");
var userVersion = editElem.innerHTML;
localStorage.userEdits = userVersion;
document.getElementById("update").innerHTML="Edits saved!";
}
function checkEdits() {
if(localStorage.userEdits!=null)
document.getElementById("edit").innerHTML=localStorage.userEdits;
}
the way i tried to edit(im new to javascript i have no idea what i was doing):
JavaScript
<script type="text/javascript">
function saveEditsplus() {
var editElemplus = document.getElementById("editplus");
var userVersionplus = editElemplus.innerHTML;
localStorageplus.userEditsplus = userVersionhtml;
}
function checkEditsplus() {
if(localStorage.userEditsplus!=null)
document.getElementById("editplus").innerHTML=localStorageplus.userEditplus;
}
</script>
in your code, you changed the name of localStorage to localStoragePlus - but localStorage is something provided by your browser (see .
If you change it back to localStorage, it might work again.
For reference, here's the part with the renamed variable:
function saveEditsplus() {
var editElemplus = document.getElementById("editplus");
var userVersionplus = editElemplus.innerHTML;
localStorageplus.userEditsplus = userVersionhtml;
^^^^
}
By the way, you're not using localStorage correctly. If you want to save something across page reloads, you need to call "set" I learned that this is not true. sorry for the confusion. (tutorial)
Yes, looks like you have no idea what the code is doing… localStorage is a browser api, you can't just rename it (like you can't - and didn't - change document or innerHTML).
However, there's no reason to rename any of the variables at all. By using the var declarations, you made them local to each of the functions, so they won't interfere with each other anyway. All you need to change are the references to the element:
function saveEditsplus() {
var editElem = document.getElementById("editplus");
var userVersion = editElem.innerHTML;
localStorage.userEditsplus = userVersion; // no …html suffix, either
// ^^^^^^^^^^^^^ the storage reference is global, though
}
function checkEditsplus() {
if(localStorage.userEditsplus!=null)
document.getElementById("editplus").innerHTML=localStorage.userEditplus;
}
However, even better than copying the code would have been to give these functions parameters - one for the id of the element, one for the property of localStorage that is supposed to be used.
You cannot modify the localStorage (browser api)!
function saveEdits() {
var editElem = document.getElementById("edit");
var userVersion = editElem.innerHTML;
localStorage.userEdits = userVersion;
document.getElementById("update").innerHTML="Edits saved!";
}
function checkEdits() {
if(localStorage.userEdits!=null)
document.getElementById("edit").innerHTML = localStorage.userEdits;
}
This is my first SO post. I'm eternally grateful for the information this community has and shares. Thanks.
I'm coming from Flash and I'm not even sure what the right question to ask is. All I can do is lay out my code example and then explain what I am trying to do. I do not fully grasp the terms that I am trying to illustrate here so I feel it is best to omit them.
The code below is incomplete as it only includes the parts that I feel are relevant to my question. Please refer to the comments in my code to see my issue.
EDIT: Full source file here: [link removed] The console.log outputs the issue in question.
<script type="text/javascript">
var a_chests = [];
var chestID = 0;
//I'm creating a plugin to be able to make multiple instances
(function ($) {
$.fn.chestPlugin = function (option) {
//This function creates a master sprite object which many of my sprites will use
//I've simplified the features to get to the heart of my question
var DHTMLSprite = function (params) {
var ident = params.ident,
var that = {
getID: function(){
return ident;
}
};
return that;
};
//ChestSprite inherits DHTMLSprites properties and then adds a few of its own
var chestSprite = function(params) {
var ident = params.ident,
that = DHTMLSprite(params);
that.reveal=function(){
console.log(ident);
};
return that;
};
//Here I create multiple instances of the chests
var treasure = function ( $drawTarget,chests) {
for (i=0;i<chests;i++){
var cs = chestSprite({
ident: "chest"+chestID
})
console.log(cs.reveal())
//This logs "chest0", "chest1", "chest2" as the for loop executes
//This behavior is correct and/or expected!
a_chests[chestID]={id:i,ob:cs};
//I add a reference to the new chestSprite for later
chestID++;
//increment the chestID;
}
console.log(a_chests[1].ob.reveal());
//This always logs "chest2" (the last chest that is created), even though
//the logs in the for loop were correct. It seems it is referencing the
//DHTML object (since the DHTMLSprite function returns that;) and since
//there is no reference to which chest I need, it passes the last one.
//Is there any way I can pass a reference to DHTMLSprite in order to retain
//the reference to the three individual chests that are created?
//Is there another solution altogether? Thanks!!!
};
//The rest of the code.
return this.each(function () {
var $drawTarget = $(this);
treasure($drawTarget,3);
});
};
})(jQuery);
</script>
You forgot to declare `that' as a local variable, so it's being overwritten on each iteration.
var chestSprite = function(params) {
var that;
var animInterval;
...
When you write:
a_chests[chestID]={id:i,ob:cs};
You are assigning the cs object itself, not an instance of this object. If later you modify cs, this will also modify what you stored in the ob property.
I guess what you need is a closure:
for (i=0;i<chests;i++){
(function(){
var cs = chestSprite({ident: "chest"+chestID});
a_chests[chestID]={id:i,ob:cs};
})();
}
This way, each loop creates a different cs object.