How to fetch console.log data in another function .we are getting value in console for example
triggerBtm: function(btmEvtObj){
$(document).trigger(btmEvtObj);
console.log(btmEvtObj);
},
Need to fetch value of "btmEvtObj" in another function in separate file. I need to fetch value in another function placed in separate file.
Why don't you just store that value in a variable. All javascript variables declared outside of a scope are global, so they can be accessed from any function.
var eventObjectFromTrigger;
triggerBtm: function(btmEvtObj){
$(document).trigger(btmEvtObj);
eventObject = btmEvtObj;
},
Then in your other function (whether its a separate file or not), just access it...
function foo(){
$(eventObjectFromTrigger).doSomething();
}
by the syntax it looks like triggerBtm is a method contained by another object. Add a return to the method body and access it in another file by calling the method from the object.
File 1
var yourObject = {
triggerBtm: function(btmEvtObj){
$(document).trigger(btmEvtObj);
console.log(btmEvtObj);
return btmEvtObj;
},
};
File 2
var yourValue = yourObject.triggerBtm();
Try Replacing The Whole Console with user-defined function:
var console = {log: function(data){
$("#console-1").append(JSON.stringify(data)+"\n");
},
error: function(data){
$("#console-1").append(JSON.stringify(data)+"\n");
},
warn: function(data){
$("#console-1").append(JSON.stringify(data)+"\n");
}};
This example will append all console log data in div#console-1.
Related
a piece of my code
const channels = fauna.paginate(q.Match(q.Index("channels"), "true")) // Query FaunaDB database for channel list => create constant called users containing results
const channelList = channels.each(function (page) {
// Logs the page's contents,
// for example: [ Ref(Collection("test"), "1234"), ... ]
console.log(page);
});
works fine and behaves how it supposed to. however, when I try to call "channelList" from elsewhere in my code it returns {}
The console.log in the first piece of code returns what it is supposed to as well so I dont think there is anything wrong with the first chunk of code.
Here is a piece of code where I attempt to call this object
let options = {
options: {
debug: config.twitchConfig.options.debug
},
connection: {
reconnect: config.twitchConfig.options.reconnect,
secure: config.twitchConfig.options.secure
},
identity: {
username: config.twitchConfig.connection.username,
password: config.twitchConfig.connection.password
},
channels: [JSON.stringify(channelList)] // Attempt to call here, Returns {} (Empty object)
};
Is there something I'm missing? is this even possible in the first place? if its not possible whats another method i can use to achieve the same result?
Edit: From what I can gather, channelList is based off of the page response, and it seems like the page response is private to that function and cannot be referenced outside of the function. what can I do to either make it referencable outside of the function or create a constant/variable that can be accessed outside of the function containing the same information
channelList is not a function, more like it is the result of a function that prints the channels.. so after printing what is assigned to it is the result..
Try assuming it as a function and then invoking it:
const channelList = ()=>{
channels.each(function (page) {
// Logs the page's contents,
// for example: [ Ref(Collection("test"), "1234"), ... ]
console.log(page);
});
};
channelList();
Assuming the code itself does what you want it to, this should do the job
After much trial and error my answer was way simpler than me or anyone else I have spoken to thought.
Here's a step by step guide on how to fix the problem yourself if you're experiencing the same issue as I was.
Use a variable instead of a constant
declare your variable before setting it by placing var channelList; somewhere above your code that sets it
set the previously declared variable with a simple channelList = page
console.log(channelList); just to make sure its all working
Finally, call the variable where you want it, and voila! you have your variable properly called and it doesn't return {} or Undefined or [Object Object]
I have a page where i use jQuery to load some content into a div element
<div id="contents-box-in"></div>
jQuery code in page
$(document).ready(function() {
$("#contents-box-in").load("new-01.php", function() {
$('#contents-box-in').fadeIn(120);
});
var updateBoxData = function(data) {
$('#contents-box-in').fadeOut(100, function() {
$('#contents-box-in').html(data).fadeIn(130);
});
}
});
the content that i load is a form that needs to load a new page sending collected data from form
$('#form-buttons-next').click(function(e) {
var formData = new FormData($(this)[0]);
var formS = $.ajax({
url : 'new-02.php',
type : 'POST',
data : formData,
async : false,
cache : false,
processData : false,
contentType : false
});
formS.done(function(data) {
if (data != null) {
updateBoxData(data);
}
});
formS.fail(function(jqXHR, textStatus) {
alert("error");
});
});
since i do this in different step i would like to use a shared function contained in page that is loading the ajax content but i get updateBoxData is undefined
I guess that ajaxed content can't see parent container function
The easy way would be to load a different .js file containing shared function, i was wondering if is possible to access the updateBoxData from ajaxed contents
...i would like to use a shared function contained in page that is loading the ajax content but i get updateBoxData is undefined
I guess that ajaxed content can't see parent container function
No, that's not why. Your updateBoxData variable is scoped to the function it's declared in (your ready) callback. If you want it accessible globally, you'll need to make it global instead.
The problem is, though, the global namespace is already incredibly crowded. So if you put all of your useful functions there as globals, you're going to run into conflicts sooner or later.
For that reason, for now until browsers support ES2015 modules (which will take a while), I suggest giving yourself just one global symbol, something unlikely to conflict with other things, and assigning an object to it with properties for your various utility functions. E.g.:
var MyNiftyUtils = {
updateBoxData: function() {
// ...
}
};
Then you call that via MyNiftyUtils.updateBoxData. If the verbosity bothers you, no worries, just use a scoping function and assign it to a local:
(function() {
var u = MyNiftyUtils;
// ....
u.updateBoxData(/*...*/);
})();
(There are about 18 variations on that theme, this is just one of them.)
The function updateBoxData is defined inside a callback function you passed to .ready and hence its scope is limited to that function. Let us call this callback function Fx.
The click handler (the function passed to .click in the second part), which we call it Fy is defined outside of Fx and as a result does not have access to the variables defined in Fx (remember updateBoxData is a variable inside Fx).
That is why your code does not work. To get it working simply take updateBoxData out of the callback in .ready function:
$(document).ready(function() {
$("#contents-box-in").load("new-01.php", function() {
$('#contents-box-in').fadeIn(120);
});
});
function updateBoxData(data) {
$('#contents-box-in').fadeOut(100, function() {
$('#contents-box-in').html(data).fadeIn(130);
});
}
...
The rest is the same.
I am just starting to get into JavaScript and couldn't find an exact scenario like this yet on SO, so I'm going to try my luck. I have two functions in an external JS file which create video feeds on our website:
function getVideos() {
//gets a list of videos
}
//callback function automatically called by getVideos()
function response(jsonData) { //can't change this line
var resp = document.getElementById("resp"); //can change this line and any subsequent lines
//parses data and populates resp
}
Then, from the HTML side, we just call getVideos() and the video feed will be created and populated.
However, I want to be able to pass any element ID I want into response() so that we can create multiple video feeds in different places on the same page. The thing is I can't change the function declaration of response() to include another parameter. Or at least I'm not led to believe I can by the company hosting our videos.
I've tried wrapping response() with getVideos() and passing an element ID from there, but then response() doesn't get called, and the only solution I can think of is resorting to storing an element ID in a global variable, which I know is a no-no in general in JavaScript.
My question is: Do I just bite the bullet and use a global variable, or is there another way?
For more info, here is our JS code as it stands now (with the closure): http://www.thebearrocks.com/Other/js/videoFeed/createVideoFeed.js
And here is the tutorial on response() we're following from the host of our videos: http://support.brightcove.com/en/video-cloud/docs/making-media-api-calls-dynamic-script-tags
may be you can use arguments? like so:
function response(jsonData) { //callback function automatically called by getVideos()
var elemId = arguments.length<2 ? "resp" : arguments[1]+"";
var resp = document.getElementById(elemId);
//parses data and populates resp
}
or, declare second argument what has default value like this:
function response(jsonData, elemId) {
elemId = elemId || "resp";
var resp = document.getElementById(elemId);
//parses data and populates resp
}
in this case function can be called as with one or two arguments
I've tried wrapping response() with getVideos() and passing an element ID from there, but then response() doesn't get called, and the only solution I can think of is resorting to storing an element ID in a global variable, which I know is a no-no in general in JavaScript.
My question is: Do I just bite the bullet and use a global variable, or is there another way?
No. Not the id variable needs to become global, but your local response function needs to for getting called back from the JSONP script - you're going to create a closure.
You can "export" it by calling
window.response = mylocalResponseFunction; // you did name that local var "response"
I've been at this for an hour and I need help. This is kind of baffling me. Consider this explicit setup of an object in my code:
WORKING CASE:
var terms={};
terms[0]={};
terms[1]={"label":"bag","cell_src":"images/bag.jpg","clue_type":"audio","clue_src":"/audio/bus.wav"};
terms[2]={"label":"crayon","cell_src":"images/crayon.jpg","clue_type":"audio","clue_src":"/audio/car.wav"};
terms[3]={"label":"pen","cell_src":"images/pen.jpg","clue_type":"audio","clue_src":"/audio/car.wav"};
terms[4]={"label":"pencil","cell_src":"images/pencil.jpg","clue_src":"/audio/boat.wav"};
terms[5]={"label":"pencil_case","cell_src":"images/pencil_case.jpg","clue_src":"/audio/train.wav"};
terms[6]={"label":"rubber","cell_src":"images/rubber.jpg","clue_src":"/audio/taxi.wav"};
terms[7]={"label":"ruler","cell_src":"images/ruler.jpg","clue_src":"/audio/plane.wav"};
terms[8]={"label":"sharpener","cell_src":"images/sharpener.jpg","clue_src":"/audio/taxi.wav"};
window.terms= terms;
window.terms= terms; // for using globaly
if I do a console.log(window.terms[1]); I get "bag". Thats what I want.
NOT WORKING CASE
If instead of explicitly defining the values of term{}, I read in the contents from a json file and assign them to each enumerated index like this:
var terms={};
terms[0]={};
$.getJSON('content.json', function(data){
$.each(data,function(i){
//terms[i]={"label":"bag","cell_src":"images/bag.jpg","clue_type":"audio","clue_src":"/audio/bus.wav"};
terms[i+1]={"label":data[i].headword,"cell_src":data[i].image,"clue_type":"audio","clue_src":data[i].audio};
});
window.terms=terms;
});
if I do a console.log(window.terms[1]); I get an error "Uncaught TypeError: Cannot read property '1' of undefined" Note that I have an alternate attempt commented out where I eliminate the possibility that theres something weird going on with the values I am trying to pull in and I explicitly assign the same static value to all the indexes. That produces the same error.
Any ideas how this could be??
$.getJSON does not block when performing an AJAX call. You have to keep the callback chain a live.
I think you want to define terms as an array of objects. Currently you have it defined as an object with properties 1, 2, 3, etc. Syntax like var terms = {} means terms is an object and when you assign terms[1] = {"label": "bag"} you're saying "the property named 1 of object terms is {"label": "bag"}. Just change your terms declaration to this:
var terms = [];
Also, if you want to see the label property of one of the objects the log statement would looks like this:
console.log(terms[2].label);
The $.getJSON() function is just a shorthand for a call to $.ajax() to load a JSON file. Since the AJAX call is asynchronous, the execution of $.getJSON() completes, and any code after it is executed, before the data has been loaded and stored in your variable.
If you want to work with terms do so inside the success callback function that you're passing to $.getJSON().
If your code looks like this:
var terms={};
terms[0]={};
$.getJSON('content.json', function(data){
$.each(data,function(i){
//terms[i]={"label":"bag","cell_src":"images/bag.jpg","clue_type":"audio","clue_src":"/audio/bus.wav"};
terms[i+1]={"label":data[i].headword,"cell_src":data[i].image,"clue_type":"audio","clue_src":data[i].audio};
});
window.terms=terms;
});
// use window.terms here
Then it won't work, because the // use window.terms here part executes before the AJAX call has finished. You'll need to move that to a separate function and call that from the success callback:
function workWithTerms() {
// use window.terms here
}
var terms={};
terms[0]={};
$.getJSON('content.json', function(data){
$.each(data,function(i){
//terms[i]={"label":"bag","cell_src":"images/bag.jpg","clue_type":"audio","clue_src":"/audio/bus.wav"};
terms[i+1]={"label":data[i].headword,"cell_src":data[i].image,"clue_type":"audio","clue_src":data[i].audio};
});
window.terms=terms;
workWithTerms();
});
I am using jFeed to parse an RSS feed and I would like to modify an outside variable (or array) from the function executed upon "success". This is a simple version of the code:
var testVariable = "Original";
jQuery.getFeed({
url: rssFeed,
success: function(feed) {
testVariable = "New Value";
}
});
When I output "testVariable", it still has the original value "Original". Is something wrong with my code?
The purpose of this is to apply the same logic to an array instead of a variable, so I can load the feed's contents into a global Javascript array.
Any help will be greatly appreciated.