Explain where "this" points to - javascript

I'm working through the Chrome extension tutorial (full code below). There is one thing I don't understand about this, which is related to line 3 of the requestKittens method
req.onload = this.showPhotos_.bind(this);
and line 1 of the showPhotos method:
var kittens = e.target.responseXML.querySelectorAll('photo');
I'm trying to understand how e.target.responseXML points to the response XML of the request. Here's what I think so far: In the line that calls this function (3rd line of requestKittens()), this points to the kittenGenerator object, meaning that kittenGenerator is bound as the first argument for showPhotos(). So the argument e in showPhotos() should be kittenGenerator, right?
If that's true, then the first line of showPhotos()...
var kittens = e.target.responseXML.querySelectorAll('photo');
...is saying that kittenGenerator has a property target. However I checked this in the Chrome console and it doesn't - so there's a mistake in my logic. Anyone able to help?
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* Global variable containing the query we'd like to pass to Flickr. In this
* case, kittens!
*
* #type {string}
*/
var QUERY = 'kittens';
var kittenGenerator = {
/**
* Flickr URL that will give us lots and lots of whatever we're looking for.
*
* See http://www.flickr.com/services/api/flickr.photos.search.html for
* details about the construction of this URL.
*
* #type {string}
* #private
*/
searchOnFlickr_: 'https://secure.flickr.com/services/rest/?' +
'method=flickr.photos.search&' +
'api_key=90485e931f687a9b9c2a66bf58a3861a&' +
'text=' + encodeURIComponent(QUERY) + '&' +
'safe_search=1&' +
'content_type=1&' +
'sort=interestingness-desc&' +
'per_page=20',
/**
* Sends an XHR GET request to grab photos of lots and lots of kittens. The
* XHR's 'onload' event is hooks up to the 'showPhotos_' method.
*
* #public
*/
requestKittens: function() {
var req = new XMLHttpRequest();
req.open("GET", this.searchOnFlickr_, true);
req.onload = this.showPhotos_.bind(this);
req.send(null);
},
/**
* Handle the 'onload' event of our kitten XHR request, generated in
* 'requestKittens', by generating 'img' elements, and stuffing them into
* the document for display.
*
* #param {ProgressEvent} e The XHR ProgressEvent.
* #private
*/
showPhotos_: function (e) {
var kittens = e.target.responseXML.querySelectorAll('photo');
for (var i = 0; i < kittens.length; i++) {
var img = document.createElement('img');
img.src = this.constructKittenURL_(kittens[i]);
img.setAttribute('alt', kittens[i].getAttribute('title'));
document.body.appendChild(img);
}
},
/**
* Given a photo, construct a URL using the method outlined at
* http://www.flickr.com/services/api/misc.urlKittenl
*
* #param {DOMElement} A kitten.
* #return {string} The kitten's URL.
* #private
*/
constructKittenURL_: function (photo) {
return "http://farm" + photo.getAttribute("farm") +
".static.flickr.com/" + photo.getAttribute("server") +
"/" + photo.getAttribute("id") +
"_" + photo.getAttribute("secret") +
"_s.jpg";
}
};
// Run our kitten generation script as soon as the document's DOM is ready.
document.addEventListener('DOMContentLoaded', function () {
kittenGenerator.requestKittens();
});

The first parameter of bind defines the context of partial application.
req.onload = this.showPhotos_.bind(this);
works because XMLHttpRequest uses event as its first parameter on it's onload handler. That's where e.target comes from.
To give you a simple example of bind, consider the following:
function add(a, b) {
return a + b;
}
var addTwo = add.bind(null, 2);
addTwo(10); // yields 12
If you define a context for bind (ie. something else than null), then you can access that context using this within the function.

Related

SuiteScript 2.0 TypeError Cannot call method "getValue" of undefined

I'm trying to get the values from two transaction body field using this code below .
/**
*#NApiVersion 2.x
*#NScriptType UserEventScript
*#param {Record} context.currentRecord
*/
define(['N/record'],
function (msg) {
function beforeSubmit(context) {
try {
var record = context.currentRecord;
var createdDate = record.getValue({
fieldId: 'createddate'
});
var dataNecessidade = record.getValue({
fieldId: 'custbodyek_data_nece_requ_po'
});
console.log(createdDate ,dataNecessidade);
}
catch(ex){
log.error(ex);
}
}
return {
beforeSubmit : beforeSubmit,
};
});
The error raised is "TypeError: Cannot call method "getValue" of undefined"
What I'm doing wrong here?
Thank you!
There is no currentRecord property on the context passed into a user event, hence the error message telling you that record is undefined. Review the docs for the beforeSubmit entry point to find the appropriate values.
On SuiteScript 2 each entry point has different parameters so you need to check those parameters on the Help or if you use an IDE like Eclipse, you will get that information when you create a new script, so for a UserEvent script and the beforeSubmit entry point, you will get something like this:
/**
* Function definition to be triggered before record is loaded.
*
* Task #5060 : calculate PO Spent Amount and Balance in realtime
*
* #param {Object} scriptContext
* #param {Record} scriptContext.newRecord - New record
* #param {Record} scriptContext.oldRecord - Old record
* #param {string} scriptContext.type - Trigger type
* #Since 2015.2
*/
and then you can see that the context parameter doesn't have a currentRecord property, instead, it has two other parameters that you can use newRecord or oldRecord so your code can be like this:
/**
*#NApiVersion 2.x
*#NScriptType UserEventScript
*#param {Record} context.currentRecord
*/
define(['N/record'],
function (msg) {
// are you aware that you are "injecting" the 'N/record' library into the 'msg' variable ???
function beforeSubmit(context) {
try {
var record = context.newRecord;
var createdDate = record.getValue({
fieldId: 'createddate'
});
var dataNecessidade = record.getValue({
fieldId: 'custbodyek_data_nece_requ_po'
});
console.log(createdDate ,dataNecessidade);
}
catch(ex){
log.error(ex);
}
}
return {
beforeSubmit : beforeSubmit,
};
});
You try to write it like this, I always use this method to get the field value.
const bfRecord= context.newRecord;
const createdDate = bfRecord.getValue('createddate');

Code intellisense for Javascript when function param is object

const _post = params => {
instance
.post(params.url, params.data)
.then(response => {
params.onSuccess(response);
})
.catch(error => {
params.onFailure(error);
});
};
So I have this helper code written by someone else in the team.
What I am looking for is when ever some tries to call this function, It should tell them that what properties it is expecting. Such as it is expecting three keys url, data, onSuccess, onFailure
How can we achieve that. I tried looking JS Doc specs but it only let us tell that the param is object like #param {Object} param
Try
/**
* some func.
* #param {Object} params - an object.
* #param {string} params.url - a url.
* #param {Object} params.data - an object.
* #param {Function} params.onSuccess .
* #param {Function} params.onFailure .
*/
function _post(params){}

Textbox for Logmessages HTML/JS

Before creating an own solution I tried finding something which already suits my needs. I have got a node.js server where multiple clients / applications connect to. These clients will send log messages to the server which I would like to display in a panel.
Now there are some feature I that I need for a typical multiline textbox for logmessages:
I need to be able to append log messages as they will be send regularly via websockets
It should autoscrolldown unless the user is selecting text or scrolling up
It should be able to use colors and bold/regular
My question:
Is there already a solution for the above use case?
Can I give you my example? It used to be a textarea but I've refactored it to a div with little code changes.
Some highlights of the code, available on github
A custom function to send log messages:
/**
* Add a message to the gamelog
* #param {Object} options : allows custom output
* #param {String} options.message : the message to display
* #param {Boolean} options.isTimed : does the message has a timestamp in front of it?
* #param {Boolean} options.isError : is the message an error?
* #param {Boolean} options.isNewline : start the message on a new line
*/
addMessage: function (options) {
var instance = ns.instance,
audio = instance.audio,
audiofx = audio.settings.fx,
history = this.areaMessage.html();
// isTimed?
options.message = options.isTimed
? history + this.fieldClock.val() + ': ' + options.message
: history + options.message;
// isNewline?
if (options.isNewline) {
options.message = options.message + '<br />';
}
// message
this.areaMessage.html(options.message);
this.scrollTop(this.areaMessage);
// isError?
if (options.isError) {
audio.play(audiofx.error);
}
},
A scroll to top function:
/**
* Automatically scroll down (from the top)
* #param {Object} target : jQuery object
*/
scrollTop: function (target) {
target.scrollTop(99999);
target.scrollTop(target.scrollTop() * 12);
}
To use colored messages you should be able to use an HTML string:
log.addMessage({
message: '<span style="color: red;">[ERROR]</span> ',
isNewLine: false
});
log.addMessage({
message: 'the rest of the error message',
isNewLine: true
});
Feel free to use this idea to enroll your own custom message box.

Why variable assignation doesnt work as expected?

We have a collection of persons, and a collection of adresses. In each person, there's an id for the adress. We try do do a 'join-like' in JavaScript, and it's not possible to add new field in the return object.
var ret;
app.get('/tp/show/method', function (req, res) {
ret={};
User2Model.find(function(err, users) {
if(err){
console.error('Error find: '+err);
}
var last_id;
for(var user_id in users){
last_id=users[user_id]._id;
ret[last_id]=users[user_id];
}
for(var user_id in users){
AdrModel.find({ 'user_id': users[user_id]['id_adr'] },function(err, adr) {
if (err){
console.error('Error find: '+err);
}
for(var i in adr){
for(var user_id in users){
if (users[user_id].id_adr==adr[i].user_id) {
/* ok id found, so add all adresses to the result: */
/* The following line doesn't work: */
ret[users[user_id]._id]=adr;
if(users[user_id]._id==last_id){
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
res.setHeader(
'content-type', 'application/javascript'
);
json=query.callback+'('+JSON.stringify({
data:{success: 1, value: ret }
})+')';
res.send(json);
}
break;
}
}
}
});
}
});
});
The variable ret is global, so we should be able to modify it, but the return result just accept when we override some of the properties already there. It doesn't work if we try to add new properties like "addr". What am I missing?
This is a typical problem caused by trying to handle asynchronous code with synchronous means. Your entire attempt is unfixable, you need to scrap it.
One widely adopted way of handling asynchronous code without going insane is by using promises.
Here is what your code could look like if you used a promise library. For the sake of the example I'm using Bluebird here.
var findAddress = Promise.promisify(AdrModel.find);
var findUsers = Promise.promisify(User2Model.find);
// a helper function that accepts a user object and resolves the address ID
function attachAddrToUser(user) {
return findAddress({
user_id: user.id_adr
}).then(function (address) {
user.address = address;
return user;
}).catch(function (e) {
console.error("error finding address for user ID " + user.id_user, e);
});
}
findUsers().then(function (users) {
var pending = [], id_user;
for (id_user in users) {
pending.push(attachAddrToUser(users[id_user]));
}
Promise.all(pending).then(function (users) {
// all done, build and send response JSON here
}).catch(function (e) {
// don't forget to add error handling
});
});
working jsFiddle over here: http://jsfiddle.net/Tomalak/2hdru6ma/
Note: attachAddrToUser() modifies the user object that you pass to it. This is not entirely clean, but it's effective in this context.
As I indicated in comments to #Tomalak's solution above, events can also be used to manage program flow in an async environment.
Here's an alternate partial solution that uses just that approach.
Please note that of the various ways of accomplishing this goal (I know of at least three, or four if you accept that the pain of "Callback Hell" can be ameliorated through the use of callbacks defined outside of and only referenced inline by their caller), I prefer using events since they are a more natural way for me to think about this class of problem.
Take-aways
Events are an efficient and easily understandable way to manage program flow in an async programming environment.
Rather than simple triggers, events can be used transport any data so they can be used further on for any purpose.
Events can easily call other events without worrying about scope.
Event processing allows you to unwind your code such that it becomes easier to track, and thus debug, as well as reducing the burden on the stack typically seen in deeply nested or recursive code. In other words, events are fast and very memory efficient.
Explanation
The code first defines two mocks:
an App class which provides a get method, allowing us to mock out the OP's app instance, and
a User2Model singleton that provides a find function for the same purpose.
It then documents the following events:
error - which is called on any errors to print a message to console and exit the program
get - which is fired with the result of the app.get method and immediately fires the processUsers event with {req:req,res:res}
processUsers - fired by the get event handler with a mocked array of user objects, sets up a results object and a last_id value, and then calls the nextUser event.
nextUser - fired by the processUsers event which picks the next user off the users array, sets evt.last_id, adds the user to the evt.results, and emits itself, or if there are no users left on the evt.users array, emits complete
complete - fired by nextUser and simply prints a message to console.
Event handlers are next defined using the 'on'+eventName convention.
And finally, we
define an eventHandlers object, to map handlers to their appropriate events,
instantiate our app instance, and
invoke its get method with a callback that simply emits a get event to start the ball rolling.
I've documented most of the solution using jsdoc and added logging messages to show progress as each event is emitted and its handler invoked. The result of the run is included after the code. (The http req and res objects have been commented out of the log messages for the sake of brevity.)
One final note, while this example is 269 lines long, most of it is documentation.
The actual code (without the mocks) is only about 20 or 25 lines.
Code
/*
Example of using events to orchestrate program flow in an async
environment.
*/
var util = require('util'),
EventEmitter = require('events').EventEmitter;
// mocks
/**
* Class for app object (MOCK)
* #constructor
* #augments EventEmitter
*/
var App = function (handlers) {
EventEmitter.call(this);
this.init(handlers);
};
util.inherits(App, EventEmitter);
/**
* Inits instance by setting event handlers
*
* #param {object} handlers
* #returns {App}
*/
App.prototype.init = function (handlers) {
var self = this;
// set event handlers
Object.keys(handlers).forEach(function (name) {
self.on(name, handlers[name]);
});
return self;
};
/**
* Invokes callback with req and res
* #param uri
* #param {App~getCallback} cb
*/
App.prototype.get = function (uri, cb) {
console.log('in app.get');
var req = {uri: uri},
res = {uri: uri};
/**
* #callback App~getCallback
* #param {object} req - http request
* #param {object} res - http response
* #fires {App#event:get}
*/
cb(req, res);
};
/**
* Data access adapter - (MOCK)
* #type {object}
*/
var User2Model = {};
/**
*
* #param {User2Model~findCallback} cb
*/
User2Model.find = function (cb) {
var err = null,
users = [
{_id: 1},
{_id: 2}
];
/**
* #callback User2Model~findCallback
* #param {Error} err
* #param {Array} users
*/
cb(err, users);
};
// events
/**
* Error event.
*
* #event App#error
* #type {object}
* #property {object} [req] - http request
* #property {object} [res] - http response
* #property {string} where - name of the function in which the error occurred
* #property {Error} err - the error object
*/
/**
* Get event - called with the result of app.get
*
* #event App#get
* #type {object}
* #property {object} req - http request
* #property {object} res - http response
*/
/**
* ProcessUsers event - called
*
* #event App#processUsers
* #type {object}
* #property {object} req - http request
* #property {object} res - http response
* #property {Array} users - users
*/
/**
* NextUser event.
*
* #event App#nextUser
* #type {object}
* #property {object} req - http request
* #property {object} res - http response
* #property {Array} users
* #property {*} last_id
* #property {object} result
*/
/**
* Complete event.
*
* #event App#complete
* #type {object}
* #property {object} req - http request
* #property {object} res - http response
* #property {Array} users
* #property {*} last_id
* #property {object} result
*/
// event handlers
/**
* Generic error handler
*
* #param {App#event:error} evt
*
* #listens App#error
*/
var onError = function (evt) {
console.error('program error in %s: %s', evt.where, evt.err);
process.exit(-1);
};
/**
* Event handler called with result of app.get
*
* #param {App#event:get} evt - the event object
*
* #listens App#appGet
* #fires App#error
* #fires App#processUsers
*/
var onGet = function (evt) {
console.log('in onGet');
var self = this;
User2Model.find(function (err, users) {
if (err) {
console.log('\tonGet emits an error');
return self.emit('error', {
res:evt.res,
req:evt.req,
where: 'User2Model.find',
err: err
});
}
self.emit('processUsers', {
//req:req,
//res:res,
users: users
});
});
};
/**
* Handler called to process users array returned from User2Model.find
*
* #param {App#event:processUsers} evt - event object
* #property {object} req - http request
* #property {object} res - http response
* #property {Array} users - array of Users
*
* #listens {App#event:processUsers}
* #fires {App#event:nextUser}
*/
var onProcessUsers = function (evt) {
console.log('in onProcessUsers: %s', util.inspect(evt));
var self = this;
evt.last_id = null;
evt.result = {};
self.emit('nextUser', evt);
};
/**
* Handler called to process a single user
*
* #param evt
* #property {Array} users
* #property {*} last_id
* #property {object} result
*
* #listens {App#event:nextUser}
* #emits {App#event:nextUser}
* #emits {App#event:complete}
*/
var onNextUser = function (evt) {
var self = this;
console.log('in onNextUser: %s', util.inspect(evt));
if (!(Array.isArray(evt.users) && evt.users.length > 0)) {
return self.emit('complete', evt);
}
var user = evt.users.shift();
evt.last_id = user._id;
evt.result[evt.last_id] = user;
self.emit('nextUser', evt);
};
/**
* Handler invoked when processing is complete.
*
* #param evt
* #property {Array} users
* #property {*} last_id
* #property {object} result
*/
var onComplete = function (evt) {
console.log('in onComplete: %s', util.inspect(evt));
};
// main entry point
var eventHandlers = { // map our handlers to events
error: onError,
get: onGet,
processUsers: onProcessUsers,
nextUser: onNextUser,
complete: onComplete
};
var app = new App(eventHandlers); // create our test runner.
app.get('/tp/show/method', function (req, res) { // and invoke it.
app.emit('get', {
req: req,
res: res
});
/* note:
For this example, req and res are added to the evt
but are ignored.
In a working application, they would be used to
return a result or an error, should the need arise,
via res.send().
*/
});
Result
in app.get
in onGet
in onProcessUsers: { users: [ { _id: 1 }, { _id: 2 } ] }
in onNextUser: { users: [ { _id: 1 }, { _id: 2 } ], last_id: null, result: {} }
in onNextUser: { users: [ { _id: 2 } ],
last_id: 1,
result: { '1': { _id: 1 } } }
in onNextUser: { users: [],
last_id: 2,
result: { '1': { _id: 1 }, '2': { _id: 2 } } }
in onComplete: { users: [],
last_id: 2,
result: { '1': { _id: 1 }, '2': { _id: 2 } } }
Well, I get it. If the function AdrModel.find is async, you're setting this values always to the last user.
This occurs because a async function will be executed after the for block end. So, the value of the user_id in all AdrModel.find calls will be always the same, because the saved scope where the async call is executed. Let's say your users are this collection
[{_id: 0}, {_id:2}, {_id: 3}]
So the calls of AdrModel.find will always use user_id -> 3 value:
ret[users[user_id]._id]=adr; //this guy will use user_id == 3, three times
EDIT
To resolve your problem is simple, modularize your code.
Create a function to do this resource gathering:
function setAdr(userId){
AdrModel.find({ 'user_id': userId },function(err, adr) {
...
}
}
And then, you call it in your 'for':
...
for(var user_id in users){
setAdr(users[user_id].id_adr);
...
This way you'll save a safe scope for each async call.

How to get browser diagnostics

I'm adding a bug report form to my project. When the user hits the send button on the form (after they explain what the bug is) I am getting information of their browser automatically. I'm currently able to get their user-agent and the source code of the page, but I think it would be super useful if I could also get any errors that have been sent to the browser console.
I've googled for stuff like "javascript get console.log content" but haven't really found anything useful.
I read about creating a "wrapper" for window.log, and found this code:
window.log = function(){
log.history = log.history || []; // store logs to an array for reference
log.history.push(arguments);
if(this.console){
console.log( Array.prototype.slice.call(arguments) );
}
};
But it doesn't seem to be getting the errors that the browser (chrome) sends to the console.log.
Does anyone know how I can get ALL of the errors in the console.log?
This seemed like an interesting idea. What I came up with is essentially a small JavaScript class that overrides the console's functions (but allows the default behavior - you can still see the information in Google Chrome's Inspector, for example).
It is pretty simple to use. Save this as 'consolelogger.js':
/**
* ConsoleLogger
*
* Tracks the history of the console.
* #author Johnathon Koster
* #version 1.0.0
*/
var ConsoleLogger = function() {
// Holds an instance of the current object.
var _instance = this;
this._logOverwrite = function(o) {
var _log = o.log;
// Overwrites the console.log function.
o.log = function(e) {
_instance.pushLog(e);
// Calls the console.log function (normal browser behavior)
_log.call(o, e);
}
// Overwrites the console.info function.
o.info = function(e) {
_instance.pushInfoLog(e);
// Calls the console.info function (normal browser behavior)
_log.call(o, e);
}
// Overwrites the console.warn function.
o.warn = function(e) {
_instance.pushWarnLog(e);
// Calls the console.warn function (normal browser behavior)
_log.call(o, e);
}
// Overwrites the console.error function.
o.error = function(e) {
_instance.pushErrorLog(e);
// Calls the console.error function (normal browser behavior)
_log.call(o, e);
}
}(console);
// Holds the history of the console calls made by other scripts.
this._logHistory = [];
this._infoHistory = [];
this._warnHistory = [];
this._errorHistory = [];
this._windowErrors = [];
/**
* This allows users to get the history of items not explicitly added.
*/
window.onerror = function(msg, url, line) {
_instance._windowErrors.push('Message: ' + msg + ' URL: ' + url + ' Line: ' + line);
}
/**
* Adds an item to the log history.
*
* #param {log} object to log
*/
this.pushLog = function(log) {
this._logHistory.push(log);
}
/**
* Adds an item to the information log history.
*
* #param {log} object to log
*/
this.pushInfoLog = function(log) {
this._infoHistory.push(log);
}
/**
* Adds an item to the warning log history.
*
* #param {log} object to log
*/
this.pushWarnLog = function(log) {
this._warnHistory.push(log);
}
/**
* Adds an item to the error log history.
*
* #param {log} object to log
*/
this.pushErrorLog = function(log) {
this._errorHistory.push(log);
}
/**
* Returns the log history.
* #this {ConsoleLogger}
* #return {array} the log history.
*/
this.getLog = function() {
return this._logHistory;
}
/**
* Returns the information log history.
* #this {ConsoleLogger}
* #return {array} the information log history.
*/
this.getInfoLog = function() {
return this._infoHistory;
}
/**
* Returns the warning log history.
* #this {ConsoleLogger}
* #return {array} the warning log history.
*/
this.getWarnLog = function() {
return this._warnHistory;
}
/**
* Returns the error log history.
* #this {ConsoleLogger}
* #return {array} the error log history.
*/
this.getErrorLog = function() {
return this._errorHistory;
}
/**
* Returns the window log history.
* #this {ConsoleLogger}
* #return {array} the window log history.
*/
this.getWindowLog = function() {
return this._windowErrors;
}
/**
* Returns all log histories.
* #this {ConsoleLogger}
* #return {array} the error log(s) history.
*/
this.getLogHistory = function() {
var _return = [];
_return = this._logHistory
_return = _return.concat(this._infoHistory);
_return = _return.concat(this._warnHistory);
_return = _return.concat(this._errorHistory);
_return = _return.concat(this._windowErrors);
return _return;
}
}
And add it to your page like this:
<script src="consolelogger.js"></script>
<script>
// Create a new instance of ConsoleLogger
var logger = new ConsoleLogger;
</script>
Now, you don't have to do anything special to trap 'console.log', 'console.warn', 'console.info', or 'console.error'. The ConsoleLogger will do it for you, and allow you to get the history of what's been added.
To retrieve the history call these functions (all of them return a JavaScript array):
var logHistory = logger.getLog(); // Get the console.log history
var infoHistory = logger.getInfoLog(); // Get the console.info history
var warningHistory = logger.getWarnLog(); // Get the console.warn history
var errorHistory = logger.getErrorLog(); // Get the console.error history
var windowLog = logger.getWindowLog(); // Get the window error history
var allLogs = logger.getLogHistory(); // Returns all log histories as one array.
I apologize for such a lengthy post, but it seems to do the trick! I also created a GitHub repo; if I do any more work on it, changes will be committed there.

Categories