Logging in google closure and dumping objects to console like console.log(myObject) - debugging

I like to dump objects to console sometimes so I can click on it and inspect it. For example:
console.log(document.body);
In closere it seems the logs log everything to console under every group (Errors, warning, Info...). But does not dump the object. Instead the formatters turn it into a string first and then display that.
Using goog.debug.expose helps somewhat but might create huge amounts of text instead of neat clickable line to use for inspection like FireBug/Chrome does.
To solve this I have commented out some code in goog/debug/logger.js
// goog.global['console']['timeStamp'](msg);
...
// goog.global['console']['markTimeline'](msg);
When I log I use the google.debug.Logger for short messages and wrote a function for dumping objects to console. Here is an example: (some of the variables are global so I can play with it in FireBug)
goog.require('goog.debug');
goog.require('goog.debug.DivConsole');
goog.require('goog.debug.Logger');
var con;
var l;
// dump object to firebug or chrome console for clickable inspection
var dumpToConsole=function(o){
try{
goog.global['console']['log'](o);
}catch(e){
l.warn("Cannot dump object to console."+
goog.debug.deepExpose(o, true));
}
}
var demoDebug = function() {
var el=document.createElement("div");
el.style.maxHeight="50px";
el.style.overflow="auto";
document.body.appendChild(el);
con=new goog.debug.DivConsole(el);
con.setCapturing(true);
l = goog.debug.Logger.getLogger('myApp.translate');
l.info("info");
l.log("log");
//dump object to console:
dumpToConsole(document.body);
}
...
//in another script block later in the page:
demoDebug();
My question is:
Is this a good way to do the logging?
Plan to put all the logging code in if (goog.DEBUG) { block so it won't be compiled when deploying the application.

Related

how the nativescript radlist view load on demand works

This might not be the question but it was the list of doubts which comes when learning native script from scratch.
I had a 1000 or more list of data stored in data table. know i want to display it on a list view but i don't want to read all the data at once. because i have images stored in other directory and want to read that also. So, for 20 to 30 data's the performance is quite good. but for 1000 data it is taking more than 15 minutes to read the data as well as images associated with it. since i'm storing some high quality images.
Therefore i decided to read only 20 data's with their respective images. and display it on list. know when user reaches the 15th data of the list. i decided to read 10 more data from the server.
know when i search this i came across "RadListView Load on Demand".
then i just looked at the code below.
public addMoreItemsFromSource(chunkSize: number) {
let newItems = this._sourceDataItems.splice(0, chunkSize);
this.dataItems.push(newItems);
}
public onLoadMoreItemsRequested(args: LoadOnDemandListViewEventData) {
const that = new WeakRef(this);
const listView: RadListView = args.object;
if (this._sourceDataItems.length > 0) {
setTimeout(function () {
that.get().addMoreItemsFromSource(2);
listView.notifyLoadOnDemandFinished();
}, 1500);
args.returnValue = true;
} else {
args.returnValue = false;
listView.notifyLoadOnDemandFinished(true);
}
}
In nativescript if i want to access binding element xml element. i must use observables in viewmodel or exports.com_name on associated js file.
but in this example it is started with public..! how to use this in javascript.
what is new WeakRef(this) ?
why it is needed ?
how to identify user has scrolled to 15 data, as i want to load more data when he came at 15th data.
after getting data how to update array of list and show it in listview ?
Finally i just want to know how to use load on demand
i tried to create a playground sample of what i have tried but it is giving error. it cannot found module of radlistview.
Remember i'm a fresher So, kindly keep this in mind when answering. thank you,
please modify the question if you feel it is not upto standards.
you can check the updated answer here
https://play.nativescript.org/?template=play-js&id=1Xireo
TypeScript to JavaScript
You may use any TypeScript compiler to convert the source code to JavaScript. There are even online compilers like the official TypeScript Playground for instance.
In my opinion, it's hard to expect ES5 examples any more. ES6-9 introduced a lot of new features that makes JavaScript development much more easier and TypeScript takes JavaScript to next level, interpreter to compiler.
To answer your question, you will use the prototype chain to define methods on your class in ES5.
YourClass.prototype.addMoreItemsFromSource = function (chunkSize) {
var newItems = this._sourceDataItems.splice(0, chunkSize);
this.dataItems.push(newItems);
};
YourClass.prototype.onLoadMoreItemsRequested = (args) {
var that = new WeakRef(this);
var listView = args.object;
if (this._sourceDataItems.length > 0) {
setTimeout(function () {
that.get().addMoreItemsFromSource(2);
listView.notifyLoadOnDemandFinished();
}, 1500);
args.returnValue = true;
} else {
args.returnValue = false;
listView.notifyLoadOnDemandFinished(true);
}
}
If you are using fromObject syntax for your Observable, then these functions can be passed inside
addMoreItemsFromSource: function (chunkSize) {
....
};
WeakRef: It helps managing your memory effiencetly by keeping a loose reference to the target, read more on docs.
How to load more:
If you set loadOnDemandMode to Auto then loadMoreDataRequested event will be triggered whenever user reaches the end of scrolling.
loadOnDemandBufferSize decides how many items before the end of scroll the event should be triggered.
Read more on docs.
How to update the array:
That's exactly what showcased in addMoreItemsFromSource function. Use .push(item) on the ObservableArray that is linked to your list view.

Elegant Protractor Logging on browser.wait()

For some time now, our team has been using the Protractor/Jasmine combo in order to do E2E testing and it has worked out great for us.
Recently, I've been assigned the task of improving the logging and have noticed 2 areas in our code where the logging could be improved.
One of these areas is with using browser.wait(). We're currently using the method in the form of browser.wait(condition, timeOut) and excluding the third parameter which is a message to be written to the console in case of a failure.
I decided to comb the code and insert a message into each of these methods and the result has been OK. Although the code works, I'm wondering if there is a more elegant way of doing this.
I'm currently saving the XPath of whatever element I'm waiting on and then if that fails, displaying a message in the form: getWait() timeout due to <element_name> { XPath = <element_XPath> } being not visible or enabled such that you can click it. The pattern changes if we're using isPresent(), elementToBeClickable(), visibilityOf(), etc.
Is there a way of getting the current context of the code I'm executing when browser.wait() is executed? Can I instead display the element or more information on what caused the timeOut?
Let me know if I can clarify further. Thanks
Even I came faced the same problem when using browser.wait where it won't show any detailed log on time out. So what I have done is, I created a wrapper class for waitHandling and added failure messages based on the wait type. Kindly have a look at below code.
var browserWaitHandler = function () {
var expectedConditions = protractor.ExpectedConditions;
var defaultWaitTime = 5000;
this.waitForElementPresent = function (_element,customWaitTime) {
return browserWait(expectedConditions.presenceOf(_element),customWaitTime,"Wait timeout after waiting for element to be Present with locator "+_element.locator().toString());
};
this.waitForElementVisible = function (_element,customWaitTime) {
return browserWait(expectedConditions.visibilityOf(_element),customWaitTime,"Wait timeout after waiting for element to be Visible with locator "+_element.locator().toString());
};
this.waitForElementClickable = function (_element,customWaitTime) {
return browserWait(expectedConditions.elementToBeClickable(_element),customWaitTime,"Wait timeout after waiting for element to be clickable with locator "+_element.locator().toString())
};
this.waitForElementContainsText = function (_element,expectedText,customWaitTime) {
return browserWait(expectedConditions.textToBePresentInElement(_element,expectedText),customWaitTime,"Wait timeout after waiting for element to Contain text as "+expectedText+" with locator "+_element.locator().toString())
};
var browserWait = function (waitCondition,customWaitTime,timeoutMessage) {
return browser.wait(waitCondition,customWaitTime | defaultWaitTime,timeoutMessage);
};
};
And also in protractor we have a method called locator() which can be used with ElementFinder and ElementArrayFinder objects to get the locator that is used to find the element.Refer below example code,
var loginButton = element(by.buttonText("Login"));
console.log("Locator used for login button is:"+loginButton.locator().toString());
*OUTPUT:*
Locator used for login button is:by.buttonText("Login")

Get Firefox to run XUL type script on startup

With Firefox 17.0.1 I am using an add-on called KeyConfig 20110522 to set some new hot keys and also set the acceltext of menuitems for my new keys as well as for add-ons that do not bother to do so.
I want the acceltext of the menuitems to be set when Firefox starts, but currently I am just using a hot key to execute the following code against the UI via KeyConfig:
document.getElementById("tabmix-menu")
.setAttribute("acceltext","Alt+Ctrl+Shift+T");
// more of the same...
I need a couple of beginners tips:
How can I execute arbitrary code against the UI in the same way as I execute against an HTML page via the console?
Is there a sneaky way to get a clump of code to execute on browser start-up without delving into XUL development?
Is there a way to trace commands executed against the UI so I can get at command calls instead of using triggers when I set my hot keys like so:
document.getElementById("tabmix-menu").click();
Any other tips on this type of low-level hacking would also be welcome.
You can execute arbitrary code against the Firefox UI from an addon, but as you say, doing all the XUL related stuff is a bit boring :-)
Enter "Bootstrapped" extensions!
Part 1:
A "Bootstrapped" (or re-startless) extension needs only an install.rdf file to identify the addon, and a bootstrap.js file to implement the bootstrap interface.
Bootstrapped Extension: https://developer.mozilla.org/en-US/docs/Extensions/Bootstrapped_extensions
Good example: http://blog.fpmurphy.com/2011/02/firefox-4-restartless-add-ons.html
The bootstrap interface can be implemented very simply:
function install() {}
function uninstall() {}
function shutdown(data, reason) {}
function startup(data, reason) { /* YOUR ARBITRARY CODE HERE! */ }
You compile the extension by putting install.rdf and bootstrap.js into the top-level of a new zip file, and rename the zip file extension to .xpi.
Part 2:
Your code is privileged and can use any of the Mozilla platform APIs. There is however an issue of timing. The moment-in-time at which the "startup" function is executed is one at which no Chrome window objects exist yet!
If it's important for your code that you have a Chrome Window, we need to wait for it to appear:
// useful services.
Cu.import("resource://gre/modules/Services.jsm");
var loader = Cc["#mozilla.org/moz/jssubscript-loader;1"]
.getService(Ci.mozIJSSubScriptLoader);
var wmSvc = Cc["#mozilla.org/appshell/window-mediator;1"]
.getService(Ci.nsIWindowMediator);
var logSvc = Cc["#mozilla.org/consoleservice;1"]
.getService(Ci.nsIConsoleService);
// get the first gBrowser
var done_startup = 0;
var windowListener;
function do_startup(win) {
if (done_startup) return;
done_startup = 1;
wmSvc.removeListener(windowListener);
var browserEnum = wmSvc.getEnumerator("navigator:browser");
var browserWin = browserEnum.getNext();
var tabbrowser = browserWin.gBrowser;
/* your code goes here! */
}
// window listener implementation
windowListener = {
onWindowTitleChange: function(aWindow, aTitle) {},
onCloseWindow: function(aWindow) {},
onOpenWindow: function(aWindow) {
var win = aWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
win.addEventListener("load", function(aEvent) {
win.removeEventListener("load", arguments.callee, false);
if (aEvent.originalTarget.nodeName != "#document") return;
do_startup();
}
};
// CODE ENTRY POINT (put this in bootstrap "startup" function)
wmSvc.addListener(windowListener);

Scoped javascript callback in scala lift

So I've been playing around with Lift in Scala, and I've been enjoying it a lot. I might just be missing something that exists in the lift javascript library, but I haven't been able to find any way of using a scoped javascript callback. It seems that the lift way of handling callbacks is to pass the callback as function name and have lift return a JsCmd that Call()s the function.
My lift code is heavily based on this example http://demo.liftweb.net/json_more
And my javascript looks kinda like
function operation(config) {
var actions = config.actions,
action = actions.shift(),
name = config.name;
function chainAction(response) {
if (actions.length > 0) {
action = actions.shift();
action.action(name, chainAction);
}
}
action.action(name, chainAction);
}
operation({
name: "ajax",
actions: [
{ action: ajaxCall1 },
{ action: ajaxCall2 }
]
});
Where I'd want ajaxCall1 and ajaxCall2, to be AJAX calls to lift. i.e. callNoParam() in the lift example, and chainAction to be the scoped callback. Is there a way to do this in lift that I'm missing? For clarity, I have been able to get this code to call the lift function, but not to handle the callback correctly.
Thanks.
Edit
Upon reading through the lift-generated javascript code, it looks like there are indeed placeholders for success/failure callbacks. In particular, it looks like this line of lift
AllJsonHandler.is.jsCmd
is generating this line of javascript
function F86737576748N5SY25(obj) {liftAjax.lift_ajaxHandler('F86737576748N5SY25='+ encodeURIComponent(JSON.stringify(obj)), null,null);}
which references this method
lift_ajaxHandler: function(theData, theSuccess, theFailure, responseType)
But not allowing me to pass theSuccess or theFailure which look like they are being passed along into jQuery.ajax() calls. My investigation continues. If anyone has any good resources on is.jsCmd it would be appreciated.
Below is a piece of code that adds a Javascript function doCallback to the page (in #placeholder). This function will print a line to the console and then do an ajaxCall back to the server to the function commandCallback.
def addExecuteCallback(ns: NodeSeq):NodeSeq = {
val log = JsRaw("console.log('[doCallback] Generated from Lift.');").cmd &
SHtml.ajaxCall(JsRaw("commandString"), commandCallback _)._2.cmd
val f = JsCmds.Function("doCallback", List[String](), log)
("#placeholder" #> JsCmds.Script(f)).apply(ns)
}
At the end of commandCallback, you can return:
JsCmds.Run("chainAction('" + valueOfResponse + "');")

Load an external JS library into a page using Greasemonkey

I want a translator in my Firefox. I find some code from internet. but it doesn't run in my Firefox. I have installed Greasemonkey.
function loadBingTranslator() {
script = document.createElement('script');
script.src = 'http://dict.bing.com.cn/cloudwidget/Scripts/Generated/BingTranslate_Selection_ShowIcon.js';
script.onload = initBingTranslator;
document.body.appendChild(script);
};
function initBingTranslator() {
BingCW.Init({
MachineTranslation: true,
WebDefinition: true
});
}
loadBingTranslator();
Such a script must account for the GM sandbox, and also (usually) allow time for the library to load and initialize.   See Avoid Common Pitfalls (in Greasemonkey).
So, you would use this library like so:
//--- Load the library.
var D = document;
var appTarg = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
var jsNode = D.createElement ('script');
jsNode.src = 'http://dict.bing.com.cn/cloudwidget/Scripts/Generated/BingTranslate_Selection_ShowIcon.js';
jsNode.addEventListener ("load", initBingTranslatorOnDelay, false);
appTarg.appendChild (jsNode);
//--- Allow some time for the library to initialize after loading.
function initBingTranslatorOnDelay () {
setTimeout (initBingTranslator, 666);
}
//--- Call the library's start-up function, if any. Note needed use of unsafeWindow.
function initBingTranslator () {
unsafeWindow.BingCW.Init ( {
AppID: "GM Foo",
MachineTranslation: true,
WebDefinition: true
} );
}
Issues, some specific to this question:
onload is not available; See the pitfalls. Event handlers cannot be set this way in GM. Also, addEventListener() is the best practice anyway.
Accessing JS (including libraries we load) in the page scope, requires unsafeWindow.
That app appears to want an AppID.
Sometimes, libraries like this can be loaded in the GM scope instead of the page scope, using the // #require directive.
I did not try that with this library, but with others, it may be possible.   Do not try this with untrusted libraries, as they gain extra abilities to infect your machine, once inside the GM scope.
Don't use reserved words, like "script", for variable names.
My JavaScript Console is outputting a "Component is not available"
line 10: script.onload = initBingTranslator;
So I fixed changed it to ... = initBingTranslator() because it is a function.
Now it says "BingCW is not definded"
Line 15: BingCW.Init({
MachineTranslation: true,
WebDefinition: true
});
And it is right, not sure if something is missing or this is supposed to only work in IE, I would find a Google translator solution personally (or just use an existing add-on).
Bing Dictionary hasd published a Firefox addon.
You can use it directly.

Resources