Object properties not updated - javascript

I have an object with a function that updates the variables of the object. I would like to use this function as a constructor too, so I can define the properties inside it. If I only define the properties within this function other functions don't realize about the change.
I mean, this.property returns undefined.
The object looks like this:
function LastRow_(sheet)
{
var lastCol,firstRowVals,rowNumber,headers;
this.rowValues;
updateObject();
// Logger.log(headers);
/*Returns the value of a specific column within last row.
It accepts header name or column letter in A1 notation*/
this.getColValue=function(column)
{
updateObject();
Logger.log(this.rowValues);
var index=getColNumber(column);
if(index>-1) return this.rowValues[index];
Logger.log("Can't find header, trying with: "+column+rowNumber);
return sheet.getRange(column+rowNumber).getValue();
};
this.setColValue=function(column,value)
{
updateObject();
};
function getColNumber(colName){ return headers.indexOf( colName.toLowerCase() ); }
/*This function is to be sure that you are allways working with the last row
and an updated version of the headers*/
function updateObject()
{
if(lastCol!==sheet.getLastColumn())
{
Logger.log("Updating row Headers");
lastCol=sheet.getLastColumn();
firstRowVals=sheet.getRange(1,1,1,lastCol).getValues()[0];
headers=[];
for(var i=0;i<firstRowVals.length;i++)
headers.push(firstRowVals[i].toLowerCase());
Logger.log(headers);
}
if(rowNumber!==sheet.getLastRow())
{
Logger.log("Updating row Values");
rowNumber=sheet.getLastRow();
this.rowValues=sheet.getRange(rowNumber,1, 1, lastCol).getValues()[0];
Logger.log(this.rowValues);
}
};
}
Any call to the object methods produces the error
function test() {/*valueLastRow(SpreadsheetApp.getActiveSpreadsheet().getSheetByName('workedDays'),"C",5)*/
var LastRow=new LastRow_(SpreadsheetApp.getActiveSpreadsheet().getSheetByName('workedDays'));
Logger.log(LastRow.getColValue("D"));
Logger.log(LastRow.getColValue("sede"));
}
The problem is that this.rowNumber is undefined.
Thanks in advance.

Related

unable to get value that is set in a callback

I'm having an issue getting a value that is set in a callback. I initially make a call to get Quest data, then call game.state.setNPCs after the quest data has returned.
I want to get the NPC object after it has been set, but the get is returning an empty array even though setNPCs() seems to be setting the array.
You can see below, after the callback to set the result.npcs, I log out getNPCs(), and it is an Empty Array.
Even more weird, I call game.state.getNPCs() from within the GameState object after the value has been set, but it is still an empty array.
EDIT: I find if I pass in game.state.getNPCs as a callback into the initial callback setNPCs(), like so:
callback(result.npcs, game.state.getNPCs);
Then this works... But I don't want to have to pass in another callback. See below.
Initial call with game.state.setNPCs callback:
Utilities.game.quest.getQuestData({ id : stat.quest_id }, game.state.setNPCs);
Call to getQuestData:
getQuestData : function (params, setNPCcallback) {
API.Quest.getQuestData(params).done(function (result) {
if (game.state) {
game.state.setQuest(result); //Object received successfully
setNPCcallback(result.npcs, game.state.getNPCs);
console.log('NPCs', game.state.getNPCs()); //Empty array
}
});
},
GameState object:
var GameState = function(args) {
this.npcs = [];
...
};
GameState.prototype = {
constructor : GameState,
getNPCs : function () {
console.log(this.npcs); //Empty array
return this.npcs;
},
setNPCs : function (npcsArray, getNPCcallback) {
this.npcs = npcsArray;
console.log(this.npcs); //Contains Object
console.log(game.state.getNPCs()); //Empty array
console.log(getNPCcallback()); //Contains Object
},
I made a small demo to test the issue.
var Person = function () {
this.name = "someone";
}
Person.prototype.walk = function () {
console.log(this)
};
var p = new Person;
function exec(callback) {
callback(); //context is Window
callback.call(p); //context is Person {name: "someone"}
}
p.walk(); //context is Person {name: "someone"}
exec(p.walk);
When you invoke the callback from getQuestData, the context is not GameState instance. Invoking the callback with the correct context using call or apply methods, or using a callback which is bound to correct context using bind method should fix the issue.
Else you can pass the GameState instance itself and invoke gameState.callbackMethod()
which should look like the following according to previous example
function exec(instance) {
instance.walk(); //context is Person {name: "someone"}
}
exec(p);

javascript how to return a number from an object variable

So, I have a large object called con in that object, I have many variables, numbered sort of like an excel sheet, b19, b20, b21, etc.
I am trying to return a value from each one, but when I do a console log, It logs the entire function, not just the return.
Here's how the object is set up:
var con = {
b13: function(){
return 12600.535*Math.sqrt((con.b14+459.4)/459.4)
},
b14: function(){
return 20;
}
}
$(document).ready(function(){
console.log(con.b13);
});
This outputs this into the console:
function(){
return 12600.535*Math.sqrt((con.b14+459.4)/459.4)
}
So how do I format this so that it outputs the actual number in the equation?
You need to make b13 and b14 properties with a getter function:
var con = {};
Object.defineProperty(con, "b13", {
get: function() {
return 12600.535*Math.sqrt((con.b14+459.4)/459.4);
}
});
Object.defineProperty(con, "b14", {
get: function() { return 20; }
});
This will cause con.b13 and con.b14 to call the given functions, returning whatever the functions return.
Try console.log(con.b13()); . You are logging the function definition not executing it.
you don't define the properties as functions...
var con = {
b13: 239487,
b12: 923748
};
edit: if some properties need to be functions you have to call them e.g. con.b14(), not con.b14 as a property
You can simply use es5 getters/setters.
var con = {
get b13() {
return 12600.535*Math.sqrt((con.b14+459.4)/459.4);
},
get b14() {
return 20;
}
};
The problem is that your object's properties are functions, but you are trying to call them as if they were values.
For example, if you wanted correctly log con.b13's value to the console, you would need to change the command to:
console.log(con.b13());
What this does is get what con.b13 returns rather than what it is.
If you don't want to go through the hassle of adding a () next to every reference, you can modify the object and define getters like this:
var con = {
get b13() {
return 12600.535 * Math.sqrt((con.b14 + 459.4) / 459.4)
},
get b14() {
return 20;
}
}
If you define the object like this, your original command console.log(con.b13) will work as intended.

Calling a Dynamically set Function Object Property from within the Object

From within my webpage I am creating an object and trying to call a dynamically set function from within it. The dynamic function however, isn't being executed.
Here is a subset of the Object:
var LightBoxLogin = {
DialogBox: null,
SuccessFunction: null,
..........
Login: function(){
console.log(LightBoxLogin.SuccessFunction) // Displays "TestSubmit()"
LightBoxLogin.SuccessFunction(); // does nothing, should alert the page
}
}
LightBoxLogin.SuccessFunction is set with:
function SuperLightbox(functOnSuccess)
{
LightBoxLogin.SuccessFunction = functOnSuccess;
if(IsLightboxNeeded())
{
LightBoxLogin.Login();
}
else{
alert("Not needed");
}
}
And called like:
function TestSubmitHandler ()
{
SuperLightbox(TestSubmit);
}
function TestSubmit ()
{
alert('TEST SUBMIT ALL CAPS');
}
Let me know if im missing anything.
I just need to execute the function passed as a parameter initially.
Instead of the line
SuperLightBox(TestSubmit);
Use the function name as a String instead:
SuperLightBox("TestSubmit");
This means in the Login:function() this line:
LightBoxLogin.SuccessFunction();
Will be replaced with:
window[LightBoxLogin.SuccessFunction]();
This yields the results I was looking for, but beware; it only works if the desired function is accessible globally in the page.

passing an object to a function in javascript

This might seem like a noob question but I'm not sure what to do. I have function with 2 variables.
function someInfo(myVar1,myVar2)
{
this.lmyVar1=myVar1;
this.myVar2=myVar2;
}
myInstance=new someInfo("string1","string2");
function drawVariables(){
document.write(myInstance.myVar1);
document.write(myInstance.myVar2);
}
I want to use the same drawVariable() for multiple instances. I just can't figure out how the exact syntax for that. How can I make drawVariable() use a different instance of someInfo without repeating anything? Is there a simple example or tutorial I can follow?
Add an argument to the definition of function drawVariables. In the code below, this argument is called info. Now you can use info as your object inside the drawVariables function, and while calling drawVariables function, you can pass whatever instance you want to pass it. drawVariables function would now work with whatever instance you pass it while calling.
function someInfo(myVar1,myVar2)
{
this.myVar1=myVar1;
this.myVar2=myVar2;
}
// Create two separate instances
myInstance=new someInfo("string1", "string1");
myInstance2 = new someInfo("string2", "string2");
// info is the argument that represents the instance passed to this function
function drawVariables(info){
alert(info.myVar1 + ", " + info.myVar2);
}
// Call the function twice with different instances
drawVariables(myInstance);
drawVariables(myInstance2);
See http://jsfiddle.net/WLHuL/ for a demo.
function drawVariables(instance){
document.write(instance.myVar1);
document.write(instance.myVar2);
}
Would it make sense for you to do it this way?
function someInfo(myVar1, myVar2)
{
this.lmyVar1 = myVar1;
this.myVar2 = myVar2;
this.drawVariables = function ()
{
document.write(this.lmyVar1);
document.write(this.myVar2);
}
}
function Test()
{
var obj1 = new someInfo("aaa", "bbb");
var obj2 = new someInfo("xxx", "zzz");
obj1.drawVariables();
obj2.drawVariables();
}

Change var in object literal function

Hi guys I am writing some code using the object literal pattern, I have function that returns a value:
'currentLocation': function() {
var cL = 0;
return cL;
},
I then need to update the variable 'cL' from another function like this:
teamStatus.currentLocation() = teamStatus.currentLocation() + teamStatus.scrollDistance();
This part is part of another function - however I get an error back stating: invalid assignment left-hand side
I am guessing I can not update the variable in this way, could anyone suggest a better method or point me in the right direction.
Any help would be greatly appreciated.
Going to add more code to highlight what I am trying to do:
'currentLocation': function() {
var cL = 0;
return cL;
},
'increaseTable': function() {
if (teamStatus.currentLocation() <= teamStatus.teamStatusTableHeight() ) {
teamStatus.currentLocation = teamStatus.currentLocation() + teamStatus.scrollDistance();
$("#tableTrackActual").animate({scrollTop: (teamStatus.currentLocation)});
$("#tableMembers").animate({scrollTop: (teamStatus.currentLocation) });
//console.log(teamStatus.currentLocation());
teamStatus.buttonRevealer();
}
}
As you can see increaseTable should update the value of currentLocation - help this sheds more light on what I am trying to achieve.
You're writing teamStatus.currentLocation() =, which calls the function teamStatus.currentLocation and tries to assign to the return value. That isn't valid. You want just teamStatus.currentLocation = — no function call.
The variable inside your function is completely private to that function (and any functions defined within it). If you need to create a number of functions that share a set of private variables, you can do that with a closure. For instance:
var Thing = (function() {
var thingWideData;
function getData() {
return thingWideData;
}
function setData(newData) {
thingWideData = newData;
}
return {
getData: getData,
setData: setData
};
})();
What that does is create a Thing object which has getData and setData functions available for it, which get and set the completely private thingWideData variable contained by the anonymous closure. More about this pattern here and here, although the latter of those is more about private methods than private data.
What your code produces is:
0 = 0 + <some number>
Which variable do you want to update? cL? You are declaring it in the function, you cannot assign a value to it from outside. Depending on the rest of your code, you might be better off with getters and setters:
var object = {
_cL = 0,
get currentLocation() {
return this._cL;
},
set currentLocation(value) {
this._cL = value;
}
}
then you can do:
teamStatus.currentLocation = teamStatus.currentLocation + teamStatus.scrollDistance();
Update:
Regarding IE: If currentLocation should actually be just a number, it might be sufficient to just declare it as property:
var obj = {
currentLocation: 0
}

Categories