Variables inside jQuery .on() not updating - javascript

Ok so I have a jQuery .on() function that looks like this....
$("#grid").on('rowdoubleclick', function(event) {
var appData = $("#grid").jqxGrid('getrowdata', event.args.rowindex);
var appID = appData.application_id
var cellClassTitle = function(row, column, value) {
alert("VALUE: " + value + " appData.title: " + appData.title);
if (value == appData.title)
{
return "yellowCell"
}
}});
My problem is that the appData.title variable inside the cellClassTitle function only gets evaluated once, on the first doubleclick. the appData variable outside the cellClassTitle function evaluates each time a row is doubleclicked but the appData.title value inside remains the same. How can I get it to update each time the .on('rowdoubleclick') function executes?

Define the function outside the scope of the rowdoubleclick handler, e.g.
var appData = appData || {title:""};
var cellClassTitle = function(row, column, value) {
alert("VALUE: " + value + " appData.title: " + appData.title);
if (value == appData.title)
{
return "yellowCell"
}
}
$("#grid").on('rowdoubleclick', function(event) {
appData = $("#grid").jqxGrid('getrowdata', event.args.rowindex);
var appID = appData.application_id
});
Disclaimer: this is nasty, take care not to pollute the global scope! http://www.yuiblog.com/blog/2006/06/01/global-domination/

Related

The changed variable value can not be accessed after a change within the function

var getFileName = null
$('#fileInput').change(function() {
var props = $('#fileInput').prop('files'),
file = props[0]
getFileName = "" + file.name
console.log("inside function: " + getFileName)
})
// selected file
console.log("outside function: " + getFileName);
The variable is changing correctly inside the function but i can't get the changed value outside the function. I think i overlook something but i can't fix it at the moment. 😅
Like mentioned in the comments the lines are not executed in the order they are noted cause of callbacks.
You should probably do this
var getFileName = null; // global variable
$('#fileInput').change(function() {
var props = $('#fileInput').prop('files'),
file = props[0],
getFileName = "" + file.name
;
console.log("inside function: " + getFileName); // log in callback
checkOutside();
})
function checkOutside(){
// output global variable after its changed in callback of "change"-event
console.log("outside function: " + getFileName);
}

Knockout.JS : self.myObservable is not a function, issues with code order

I have page using knockout, which has a searchfield, selectedvalue from a dropdown, and pagenumber..
All these are initialized at set to defaultvalues, especially for first run / page access..
The problem is that i dont understand why i'm getting the following error
"self.selectedTeamId is not a function()"
I know.. this has to be something with the "order of things", so that when it's being used, it has NOT been initialized yet.
Can someone correct my mistake ?
CODE :
$(document).ready(function() {
var ViewModel = function() {
var self = this;
self.photos = ko.observableArray();
self.selectedTeamId = ko.observable(0);
self.searchString = ko.observable('');
self.pageNumber = ko.observable(1);
self.clearFilters = function() {
self.searchString(''); // set default to ''
self.selectedTeamId(0); // set default to 0
self.pageNumber(1); // set default to 1
self.getPhotos();
};
self.getPhotos = function () {
var photoParams = "?teamId=" + self.selectedTeamId() + "&search=" + encodeURIComponent(self.searchString()) + "&pageNumber=" + self.pageNumber();
$.get("api/Photo/GetPhotos" + photoParams,
function(data) {
self.photos(data);
}, "json");
};
};
var photosModel = new ViewModel();
ko.applyBindings(photosModel, document.getElementById("photoarchive"));
// THE NEXT LINE GIVES THE ERROR (self.selectedTeamId())
var photoParams = "?teamId=" + self.selectedTeamId() + "&search=" + encodeURIComponent(self.searchString()) + "&pageNumber=" + self.pageNumber();
$.get("api/Photo/GetPhotos" + photoParams,
function(data) {
photosModel.photos(data);
}, "json");
});
self is a variable which is local to your ViewModel function. It isn't accessible outside of that function.
As you're storing your ViewModel within your photosModel variable, you can instead access the selectedTeamId observable with:
photosModel.selectedTeamId()
You'll need to do the same with self.searchString() and self.pageNumber().
That said, however, you may as well just call photosModel.getPhotos() instead of duplicating the entire function outside of the ViewModel scope.

Accesing function within function JavaScript

I got this piece of code below which is not DRY. What i want to do is to cut it,so everything below var = text would be used only once not twice.
My concept is,to close these two functions in bigger function (e.g. guess()) and keep trimmed correctGuess() and incorrectGuess() within it.
Now here's the question,how can I call such nested function as describe above from outside scope. I was thinking about smth like: guess().correctGuess() which is obviously wrong but I wanted to share a concept.
Additionally, when e.g. correctGuess() would be called, is rest of the commands within our main guess() function would be executed?
function correctGuess(i) {
totalScore++;
questionNumber++;
var text = "Correct!";
var updatePage = ['<div id="answerDiv">' +
'<h1>' + text + '<h1>' +
'<h2>Total Score: ' + totalScore + '</h2></div>'
];
mainContent[html](updatePage);
$('#answerDiv')[fadeIn]("slow");
$('#answerDiv').append('<button id="nextButton">Next Question</button>');
$('#nextButton').on('click', function() {
if (questionNumber == allQuestions.length && totalScore <= 4) {
results()
} else {
question(questionNumber)
}
})
};
var incorrectGuess = function(i) {
totalScore--;
questionNumber++;
var text = "Wrong!";
var updatePage = ['<div id="answerDiv">' +
'<h1>' + text + '<h1>' +
'<h2>Total Score: ' + totalScore + '</h2></div>'
];
mainContent[html](updatePage);
$('#answerDiv')[fadeIn]("slow");
$('#answerDiv').append('<button id="nextButton">Next Question</button>');
$('#nextButton').on('click', function() {
if (questionNumber == allQuestions.length && totalScore <= 4) {
results();
} else {
question(questionNumber);
}
});
};
http://www.w3schools.com/js/js_objects.asp
From your question it seems like you aren't very familiar with object notation. Read up on the above link and then try to create a js "guess" object with 2 member functions. Correct and Incorrect guess.
You need to use the this keyword.
function guess(){
/* do stuff here for guess() */
this.correct = function(){
/* Do stuff for correct */
}
this.wrong = function(){
/* Do stuff for wrong */
}
return this;
}
Because you returned this you can now access the correct() and wrong() functions using:
guess().correct();
// AND
guess().wrong();
Note that whatever code you write inside guess() and outside the two nested functions will also be called every time you call guess().correct() or guess().wrong()
If you do not want any particular code to execute every time they "guess" regardless of right or wrong then I would suggest just storing the correct() and wrong() functions in an object literal.
var guess = {
correct: function(){
// Code for "correct" here
},
wrong: function(){
// Code for "wrong" here
}
}
And then you can access them using
guess.correct();
// AND
guess.wrong();

Declare public variables in Handlebar JS

I Would like to declare a global variable in my JS file and i would like to use that variable in different function in the same class .
I have declared a variable in initialize section
initialize: function () {
this.regionid="";
}
selectItems: function ()
{
this.regionid="10";
this.Regions.url = this.Regions.url() + '?requesttype=1';
this.Regions.fetch({ success: this.renderRegion });
}
renderRegion: function () {
var ddlRegionClass = this.Regions.toJSON();
$(this.el).find('[id=cboRegion] option').remove();
$.each(ddlRegionClass.LOCATIONS_Regions, function (j, cc1) {
var data = 'data='+cc1.AreaCode_2;
var selected = '';
if(cc1.AreaCode_3==this.regionid)
selected="selected";
$('[id=cboRegion]').append('<option value="' + cc1.AreaCode_3 + '" ' + data + selected + ' >' + cc1.Area_Name + '</option>');
})
},
While i am checking the value at
if(cc1.AreaCode_3==this.regionid)
i didnt get the value , it is showing 'undefined'
this.regionid="";
initialize: function () {
//some code
}
I think you have to declare like this..then it will work..you can assign values for variable in any function.
this inside the callback of $.each won't be referring to the view (or the object which the js file is containing).
In the initialize you can bind renderRegion with this:
initialize: function() {
this.regionid = "";
_.bindAll(this, "renderRegion");
}
and inside renderRegion:
renderRegion: function() {
// before doing $.each store 'this' reference
var _this = this;
// and inside the callback use if(cc1.AreaCode_3 == _this.regionid)
}
It should work.

Javascript global array with jquery .push returns empty array in alternate function

I declare a variable, outside of a function like so:
var vitalsValuesChecked = [];
then inside of a function I do:
vitalsValuesChecked.push('foobar');
In a later function I need to loop through the array for the items pushed, and constantly am not getting the result I expect. So inside that same function, I added console.log(vitalsValuesChecked); which returns [].
EDIT Code sample below;
EDIT 2 Fixed code below
var vitalsValuesChecked = [];
$(document).delegate("#hv-byresult-btn", "click", function () {
var vitalsTypeList = ['bp', 'ht', 'wt', 'pulse', 'resp', 'temp'];
vitalsValuesChecked = [];
for (var i = 0;i < vitalsTypeList.length;i++) {
if (document.getElementById(vitalsTypeList[i]).checked == true) {
vitalsValuesChecked.push(vitalsTypeList[i]);
console.log(vitalsTypeList[i] + " is checked. Adding to global array");
}
}
$('#vitals-measures-content').empty();
navigate("#vitals-measures");
for (var i = 0;i < vitalsValuesChecked.length;i++) {
console.log("vitalsValuesChecked at index " + i + " is " + vitalsValuesChecked[i]);
}
readRec('clinicalObservation', null, sortVitalsByResult);
});
function foobar() {
console.log(vitalsValuesChecked); //return []
for (var i=0;i < vitalsValuesChecked.length;i++) {
var valueSelected = vitalsValuesChecked[i];
console.log("Value of vitalsValuesChecked at index " + i + " is " + vitalsValuesChecked[i]);
}
}
You have defined vitalsValuesChecked twice which is a problem. One is global and one is local to the delegate() callback. The local definition overrides the global definition so when you thought you were setting values into the global variable, you were not - you were just changing the local variable which has a limited lifetime and thus your data was not available later in the global variable.
You should remove the
var vitalsValuesChecked = [];
inside the delegate handler so all modifications occur on the single global variable.
The var vitalsValuesChecked = []; inside the function will create a local variable. I don't think you want this if you're trying to push to the global variable.

Categories