Is there any way to call "benchmark" in the javascript code - javascript

I am trying to understand this javascript code, which extends jquery. I know calling extend on the jquery object will add a tablesorter object to the $ object.
I want to clear the cache on a tablesorter object, something like this
$("#myTable").tablesorter();
$("#myTable").buildParserCache(); //so as to clear the cache. I get undefined is not a function.
$("#myTable").tablesorter().buildParserCache() //also get undefined is not a function
Can someone explain why this is not possible and how to clear the cache. I know I am butting up against some JS design patterns and scope rules and I would like to understand them.
(function ($) {
$.extend({
tablesorter: new
function () {
var parsers = [],
widgets = [];
this.defaults = {
...
};
/* debuging utils */
function benchmark(s, d) {
log(s + "," + (new Date().getTime() - d.getTime()) + "ms");
}
function buildParserCache(table, $headers) {
if (table.config.debug) {
var parsersDebug = "";
}

The buildParserCache function is defined inside the function () which starts on the fourth line of that snippet, so it will only be accessible outside the function if it is explicitly exposed - and it looks like it isn't, so that is effectively a private function.
The methods which are exposed appear to be grouped after the /* public methods */ comment.
The this.construct = function function gets further exposed by this:
$.fn.extend({
tablesorter: $.tablesorter.construct
});
so that is the function that ends up being called when $("#myTable").tablesorter() is called.

Related

javascript namespace call other function methods

I try to change some way to call methods into namespace.
Calling parent methods (I dont think its possible)
Creating and call inheritance function
Calling inside another method (mostly jquery onReady event function) (this.MyFunction() not working)
I split every namespace in files (want to keep it that way)
I try How to call function A from function B within the same namespace? but I didn't succed to split namespaces.
my fiddle sample got only 1 sub-namespace but could be more.
https://jsfiddle.net/forX/kv1w2rvc/
/**************************************************************************
// FILE Master.js
***************************************************************************/
if (!Master) var Master = {};
Master.Print= function(text){
console.log("master.Print :" + text);
$("body").append("<div>master.Print : " + text + "</div>");
}
/**************************************************************************
// FILE Master.Test1.js
***************************************************************************/
if (!Master) var Master = {};
if (!Master.Test1) Master.Test1 = {};
/**************************************************************************
* Descrition :
* Function for managing event load/documentReady
**************************************************************************/
Master.Test1.onReady = function () {
$(function () {
Master.Test1.Function1(); //try to replace because need all namespace.
try {
this.Function2(); //not working
}
catch(err) {
console.log("this.Function2 not working");
$("body").append("<div>this.Function2 not working</div>");
}
try {
this.Print("onReady"); //not working
}
catch(err) {
console.log("this.Print not working");
$("body").append("<div>this.Print not working</div>");
}
try {
Print("onReady"); //not working
}
catch(err) {
console.log("Print not working");
$("body").append("<div>Print not working</div>");
}
});
}
Master.Test1.Function1 = function () {
console.log("Function1");
$("body").append("<div>Function1</div>");
this.Function3(); //working because not inside another function
}
Master.Test1.Function2 = function () {
$("body").append("<div>Function2</div>");
console.log("Function2");
}
Master.Test1.Function3 = function () {
$("body").append("<div>Function3</div>");
console.log("Function3");
Master.Print("Function3"); //try to replace because need all namespace.
}
Master.Test1.onReady();
I use Master.Test1.Function1(); and I want to change that because Function1 is inside the same namespace.
I use Master.Print("Function3"); I dont think I can change that. the way I try to use it, it's more an inheritance function. but I dont know if theres a way to do that?
Maybe I should change the my namespace methode? maybe prototype will do what I want?
You can capture the this in a variable because this inside $(function() {}) will point to document object. The below will work provided you never change the calling context of onReady -- i.e. it is always called on the Test1 object and not called on other context:
Master.Test1.onReady = function () {
var self = this;
$(function () {
self.Function1();
// ..
});
}
To access Print you have to reference using the Master object like: Master.Print() as it won't be available in the Test1 object
this is document within .ready() or jQuery() alias for .ready() where function(){} is parameter $(function() {}). this at this.Function2() will reference document.
"Objects" in javascript are not built the same way as in most object-oriented languages. Essentially, what you are building is a hierarchy of static methods that have no real internal state in-and-of themselves. Therefore, when one of the defined methods is invoked, the context (or state) of that method depends on what object invoked the method.
If you want to have any internal context, you will need to create an "instance" of an "object prototype". At that point, you can use "this.otherFunction" within your other functions. Here is a small example:
var MyObject = function() {};
MyObject.functionOne = function() {
console.log("Function 1");
this.functionTwo();
};
MyObject.functionTwo = function() {
console.log("Function 2");
};
var instanceOne = new MyObject();
instanceOne.functionOne();
You might get some more information about object definition here

Call function within another in Javascript

I've the following script:
gapi.analytics.ready(function() {
viewSelector.on('viewChange', function update (data) {
var title = document.getElementById('view-name');
title.innerHTML = data.property.name + ' (' + data.view.name + ')';
activeUsers.set(data).execute();
renderWeekOverWeekChart(data.ids);
renderTopBrowsersChart(data.ids);
renderTopCountriesChart(data.ids);
setTimeout(function() {
var list = document.getElementsByTagName("tr")[0];
list.getElementsByTagName("th")[0].innerHTML = "Pagina's";
list.getElementsByTagName("th")[1].innerHTML = "Paginaweergaven";
}, 500);
});
});
And within the following code I would like to re-run the update(); function.
function datumwissel( datumbtn ) {
if ( datumbtn.className == 'maand' ) {
datumbtn.className = 'jaar';
dimensions1 = 'ga:month,ga:nthMonth';
start1 = moment(now).date(1).month(0).format('YYYY-MM-DD');
end1 = moment(now).format('YYYY-MM-DD');
start2 = moment(now).subtract(1, 'year').date(1).month(0).format('YYYY-MM-DD');
end2 = moment(now).date(1).month(0).subtract(1, 'day').format('YYYY-MM-DD');
format1 = 'M';
format2 = 'MMM';
update();
}
else {
datumbtn.className = 'maand';
dimensions1 = 'ga:date,ga:nthWeek';
start1 = moment(now).subtract(2, 'day').date(1).format('YYYY-MM-DD');
end1 = moment(now).format('YYYY-MM-DD');
start2 = moment(now).subtract(2, 'day').date(1).subtract(1, 'month').format('YYYY-MM-DD');
end2 = moment(now).subtract(2, 'day').date(1).subtract(1, 'day').format('YYYY-MM-DD');
format1 = 'YYYYMMDD';
format2 = 'Do';
update();
}
}
But somehow this doesn't work. I also tried in the above script:
window.update = function (data) {}. But that also doesn't work.
How can I call the update(); function that is situated inside the gapi.analytics.ready(function() {} ?
Important is that I cannot make it globally as it has to be situated inside the gapi.analytics.ready().
It's really a simple matter of moving the function declaration
function update (data) {
// same as existing code
}
gapi.analytics.ready(function() {
viewSelector.on('viewChange', update );
});
And passing in data needed when you call it in your other function
function datumwissel( datumbtn ) {
if ( datumbtn.className == 'maand' ) {
..........
update(datumbtn);
}.......
Important is that I cannot make it globally as it has to be situated inside the gapi.analytics.ready()
That's not actually true - you can have it global and there at the same time. Whether you want to, is a different manner, as that would pollute the global namespace and so on. However, here is how that can be achieved:
First, extract the update function outside of the ready handler like so
function update (data) {
var title = document.getElementById('view-name');
title.innerHTML = data.property.name + ' (' + data.view.name + ')';
activeUsers.set(data).execute();
renderWeekOverWeekChart(data.ids);
renderTopBrowsersChart(data.ids);
renderTopCountriesChart(data.ids);
setTimeout(function() {
var list = document.getElementsByTagName("tr")[0];
list.getElementsByTagName("th")[0].innerHTML = "Pagina's";
list.getElementsByTagName("th")[1].innerHTML = "Paginaweergaven";
}, 500);
}
This will create a new function with the name update which accepts one parameter called data. Thanks to hoisting it would not matter if it's before or after anywhere you want to use it, as it would be effectively "pulled" to the top.
Next, you can just use the function inside the ready handler like so:
gapi.analytics.ready(function() {
viewSelector.on('viewChange', update);
});
Since .on(events, handler) accepts a function as the second parameter, you can just provide a function reference there. It doesn't matter that your function is technically declared elsewhere, as it is still going to be called with the same arguments. Similarly, if you replace update with alert you will be giving the reference to window.alert so you will get an alert with data.
With that, you can just call the same function in your other piece of code.
That is true for any place that uses callbacks, including setTimeout - you can just give a function reference and it's going to be called. Internally, those kinds of functions almost always do something like callback() or callback(someData), occasionally callback.call(/* parameters */) where callback is the passed in argument. Whether you define that argument as you are calling the function, e.g., selector.on("click", function() {/* code */}) or separately, e.g.,
function clickHandler() { /* code */ }
selector.on("click", clickHandler)
matters little.
With that said, whether you want the function global is a different matter. Unless both pieces of code are in the same place, a global function may be the easiest way. You could, also, namespace anything your app uses, which would partially avoid the global pollution. Not completely, but sometimes you just need to have things living under window if you have multiple files, in which case, you can define your own little corner there to play with: window.myApp = window.myApp || {} would create a new object that can serve as namespace and so you will be able to do things like myApp.update = function(data) { /* code */ } and thus share that code.
If your two pieces of code are indeed in one file, then you merely need to create the function outside both using var update = function(data) { /* code */ } then hand it to each in the exact same way, since update is still going to be a function reference, however, if assigned to a variable, it won't be added to the global namespace (nor would the declaration be hoisted).

attache function to other function in javascript

I have a simple requirement, I need add the same code to hundreds of other JavaScript functions, the code can be executed at the end of the function, is there a handy way of doing it, like attach an function to another function dynamically, I think yes, because JavaScript is so powerful and too powerful, any ideas?
Note, I need dynamically assign new code or function to existing functions without change existing function's code, please give a solid solution, I can do it in hacky way, but no hacky way please!
The first method that comes to mind is simply create another function:
function primaryFunction() {
// ...
utilityMethod();
}
function otherPrimaryFunction() {
// ...
utilityMethod();
}
function utilityMethod() { ... }
Now utilityMethod() gets called from the end of each other primary function.
There's also a method which requires more code refactoring but is better in the long term: classes/prototypes.
Essentially, you have one "constructor" function which takes a number of parameters for the "class" and returns an class-like object:
function constructor(someClassField, anotherField) {
this.aField = someClassField;
this.fieldTwo = anotherField;
return this;
}
Now if you call this and pass some parameters, you get a class out:
var myClass = new constructor("1", "2");
myClass.aField == "1";
myClass.fieldTwo == "2";
So: If you define your utility method as above, then you can use this: for every primary function you instantiate a new instance of the constructor, with the final code looking like this:
function constructor(primaryFunction) {
this.function = primaryFunction;
this.call = function() {
this.function();
utilityMethod();
}
this.call();
return this;
}
function utilityMethod() { ... }
var primaryMethod = new constructor(function() { ... });
The creation of primaryMethod now automatically calls the primary function followed by the utility method, before returning the object so you can re-call both if you want to.

How to reference a function defined inside prototype

I am trying to add a functionality to a web page that uses a jquery library which doesn't seem to have any documentation. (unknown origin) my problem is mainly due to the lack of understanding on jquery plugin model and/or inner workings of javascript.
1. the plugin is initiated as follows
jQuery('div.carousel').scrollGallery({
mask: 'div.mask',
slider: 'div.slideset',
slides: 'div.slide', ............ });
2. the plugin is defined in jquery as follows
;(function($){
function ScrollGallery(options) {
this.options = $.extend({
mask: 'div.mask', ...... }, options);
this.init();
3. in the Object.prototype declaration i see the following function numSlide defined.
ScrollGallery.prototype = {
....................
numSlide: function(c) {
if(this.currentStep != c) {
this.currentStep = c;
this.switchSlide();
}
},
.......... };
Question.
How do i reference numSlide(int) function externally?.
I tried the following methods and it did not work.
myx = jQuery('div.carousel').scrollGallery({ // var myx was added in the global scope
myx.numSlide(1); //error undefined is not a function
i tried adding return this; at the end of myx = jQuery('div.carousel').scrollGallery({ but it still returns the jQuery object.
i also tried
jQuery.scrollGallery().numSlide(2); //error undefined is not a function
jQuery.scrollGallery.numSlide(2); //same error
Do i need to add LIGHT BULB
// jquery plugin
$.fn.scrollGallery = function(opt){
return this.each(function(){
$(this).data('ScrollGallery', new ScrollGallery($.extend(opt,{holder:this})));
});
};
}(jQuery));
ANSWER (I think)
it looks like the ScrollGalary object is stored in a data for the selector. So i believe i can do the following jQuery('selector').data('ScrollGallery').numSlide(2);
I decided to post this anyway in-case if anyone in the future had a similar gullible situation.
One way of doing this will be to initiate ScrollGallery object first and then use it.
var test = new ScrollGallery();
test.numSlide();
if you want to extend jQuery and use the function you can assign it as follows
$.fn.scrollGallery = new ScrollGallery();
and use it
$("window").scrollGallery.numSlide();

Separate a Javascript function to reuse it, how?

I see some javascript and try to implement the function seperated to reuse it.
This is the old code:
var ListRenderRenderWrapper = function(itemRenderResult, inCtx, tpl)
{
var iStr = [];
iStr.push('<li>');
iStr.push(itemRenderResult);
iStr.push('</li>');
return iStr.join('');
}
And I would like to make something like this:
function wrapItems(itemRenderResult, inCtx, tpl)
{
var iStr = [];
iStr.push('<li>');
iStr.push(itemRenderResult);
iStr.push('</li>');
return iStr.join('');
}
var ListRenderRenderWrapper = wrapItems(itemRenderResult, inCtx, tpl);
is this ok or do I need to do it in another way?
If you just want to assign that function to a new variable so you can call it with a different name, simply do:
var ListRenderRenderWrapper = wrapItems;
The confusion may be coming from the fact that in JavaScript a function can be stored inside a variable and called as a function later.
This means that:
function thing() { /* code */ }
is the same as:
var thing = function() { /* code */ }
(Aside: I know there are subtle differences with hoisting etc, but for the purposes of this example they are the same).

Categories