RSS

Tag Archives: javascript

Promises rejection (..but with style)

I find handy define this kind of function in my code:

function if_error(reject, err) {
  if (err) {
    console.error(err);
    reject(err);
  }
}

Now when I’ll need to handle a rejection, my code will be

something.can('go-wrong', (err) => {
  if_error(reject, err);
  ...

It’s something between pure functional programming and very readable code.

 
Leave a comment

Posted by on 2017/05/16 in dev

 

Tags: ,

js timestamp

Sometimes while logging js I need to have a timestamp in the beggining of the row. There are libraries to manage timestamps and to print wonderful logs, but sometimes the needs are only to make some console.log while debugging.

This is my one-line way to handle it:

function timestamp() {
  return (new Date).toISOString().match(/([0-9]{2}:[0-9]{2}:[0-9]?[0-9].[0-9]{3})/g)[0];
}

or “keep only the time part of an ISO formatted timestamp”.

 
Leave a comment

Posted by on 2016/12/16 in dev

 

Tags: , ,

this.window (& friends)

Open a console in your browser, then verify these:

console.log(this === this.window); // true
console.log(this === this.window.window.window); // true
console.log(this === this.self); // true 
console.log(this === this.frames); // true (also when this.frames.length > 0)

When this.frames.length > 0 you can also:

for (i in this.frames) console.log(this === this.frames[i]) // true,false,true,true,false,.... (so many true because we have "self","window","parent","frames",... The others are $,jQuery,google stuff,...)

console.log(this.window[0] === this.window[1]); // false
console.log(this.window[0] === this); // false (obviously in my test)
console.log(this.window[1] === this); // false (obviously in my test)
console.log(this.window[1] === this.frames[1]); // true
 
Leave a comment

Posted by on 2016/04/07 in dev

 

Tags: , , ,

Show me your events

“Which javascript event best fits my requirements?”

To answer the question let’s inspect the given element and get all its bound events:

var evts = ‚Äč$._data( $("#element")[0], "events" );

Easy as an easy thing!

 
Leave a comment

Posted by on 2014/06/04 in dev

 

Tags: ,

Javascript as C# code

One of the most handy things I created during my daily job as a .NET developer is a system to automagically include my javascript code libraries into every new project I’m going to develop. It’s a sort of javascript dll…no wait IT ACTUALLY IS a .dll file! =)
Here’s the trick…

Preparing the recipe

  • Create a new library (.dll) project … name it “My.Common.Js” (it’s just an example)
  • Include your javascript file (i.e. “myJsFile.js“) into the project
  • Include a folder that contains the minified version of the script (something like “minified/myJsFile.min.js“) into the project
  • Right click on the “myJsFile.min.js” and choose: Build Action “Embedded Resource”

Mix them all

Into the .cs file include the following (at the top, under the “using” block):

[assembly: WebResource("My.Common.Js.minified.myJsFile.min.js", "application/x-javascript")]

Let’s define a class that uses these files:

namespace My.Common
{
    public class JsUtil
(..)

The JsUtil class has one interesting private function that takes the name of a resource and create its phisical file into the given path, including its inclusion (sorry for the joke) into the given page:

private static void dumpResource(Page p, String rezname, String path, String inclPath, Boolean toTheEnd)
{
  String jsns = "My.Common.Js.minified.";
 
  // fix path
  if (!path.EndsWith(@"\")) path += @"\";
  if (!inclPath.EndsWith(@"/")) inclPath += @"/";
  String fout = path + rezname;
  String version = "?ver=1";

  // recreate the file only if needed
  if (!System.IO.File.Exists(fout))
  {
    // read the embedded resource
    String rez = String.Empty;
    System.Reflection.Assembly a = System.Reflection.Assembly.GetAssembly(typeof(JsUtils));
    Version v = a.GetName().Version;
    version = "?ver=" + v.Build.ToString();
    using (StreamReader sr = new StreamReader(a.GetManifestResourceStream(jsns + rezname)))
    {
      rez = sr.ReadToEnd();
    }

    // write it into a file
    if (!Directory.Exists(path)) Directory.CreateDirectory(path);
    try
    {
      using (StreamWriter sw = new StreamWriter(fout))
      {
        sw.Write(rez);
      }
    }
    catch
    {
      // we're racing...let them win
    }
  }

  // include it into the page 
  System.Web.UI.HtmlControls.HtmlGenericControl headctrl = new System.Web.UI.HtmlControls.HtmlGenericControl("script");
  headctrl.Attributes.Add("type", "text/javascript");
  headctrl.Attributes.Add("src", inclPath + rezname + version);
  if (toTheEnd || p.Header.Controls.Count == 0)
    p.Header.Controls.Add(headctrl);
  else
    p.Header.Controls.AddAt(0, headctrl);
}

Ok, now it’s easy. My JsUtil class exposes a very minimal static method:

public static void Include_myJsFile(System.Web.UI.Page page, String jsPath, String inclPath)
{
  dumpResource(page, "myJsFile.min.js", jsPath, inclPath, true);
}

Serve hot

Somewhere in your page:

// filesystem path
String filepath = HttpContext.Current.Server.MapPath("~") + @"\JS\my.common";
// js path
String includepath = @"../JS/my.common"; // js format
// check
if (!Directory.Exists(filepath)) Directory.CreateDirectory(filepath);
// include
JsUtils.Include_myJsFile(this, filepath, includepath);
 
Leave a comment

Posted by on 2013/12/27 in dev

 

Tags: , , , ,

true or false: it’s not a binary choice

When using javascript functions like the Array Filter Method you need to define a test over a value.
Sometimes I see that developers are confused about “what’s true” and this can generate bugs.

Let’s work with an example.
Given a function that makes some test over a parameter:

// be careful: uneval() is a Firefox non-standard feature
function doTheTest(val) {
    console.log("------------- val " + uneval(val) + " is " + typeof (val));

    if (val)  console.log('val is pseudo true');
    else console.log('val is not pseudo true');
    
    if (val == true)  console.log('val is == true' );
    else console.log('val is not == true');
    
    if (val === true)  console.log('val is === true' );
    else console.log('val is not === true');
    
    if (val != true)  console.log('val is != true' );
    else console.log('val is not != true');
    
    if (val !== true)  console.log('val is !== true' );
    else console.log('val is not !== true');

    // ..and null?
    if (val == null)  console.log('val is == null' );
    else console.log('val is not == null');
    if (val === null)  console.log('val is === null' );
    else console.log('val is not === null');
}

let’s call that function with some “stuff”:

doTheTest(42);
doTheTest(0);
doTheTest("one");
doTheTest("");
doTheTest(null);
doTheTest(); // undefined
doTheTest({a:1, b:11});
doTheTest(doTheTest); // =)

This is the Firebug’s console output, with some highlight from me:

------------- val 42 is number
val is pseudo true            <==
val is not == true
val is not === true
val is != true
val is !== true
val is not == null
val is not === null
------------- val 0 is number
val is not pseudo true            <==
val is not == true
val is not === true
val is != true
val is !== true
val is not == null
val is not === null
------------- val "one" is string
val is pseudo true
val is not == true
val is not === true
val is != true
val is !== true
val is not == null
val is not === null
------------- val "" is string
val is not pseudo true            <==
val is not == true
val is not === true
val is != true
val is !== true
val is not == null
val is not === null
------------- val null is object
val is not pseudo true
val is not == true
val is not === true
val is != true
val is !== true
val is == null
val is === null
------------- val (void 0) is undefined
val is not pseudo true
val is not == true
val is not === true
val is != true
val is !== true
val is == null            <==
val is not === null
------------- val ({a:1, b:11}) is object
val is pseudo true
val is not == true
val is not === true
val is != true
val is !== true
val is not == null
val is not === null
------------- val function doTheTest(val) { ..code removed.. } is function
val is pseudo true
val is not == true
val is not === true
val is != true
val is !== true
val is not == null
val is not === null

Did you expect these results?

 
Leave a comment

Posted by on 2013/11/06 in dev

 

Tags: , , , , , ,

Handling jQueryUI modal dialogs inside ASP.NET UpdatePanels

Some time ago I had some problem handling a modal jQueryUI dialog inside an UpdatePanel. When the dialog was closed an
TypeError: $(…).data(…) is null
.data( widgetFullName )._focusTabbable(); jquery-ui.js (line 10343)
error was raised into the FireBug console.

Here’s the the mystery solved, as published in http://forum.jquery.com:

the $.ui.dialog.overlayInstances global variable keeps tracks of every overlay created (maybe from multiple modal dialogs). This variable is initializated during the inclusion of the jqueryui.js file and its initial value is 0.
It’s a global, so you can access it from everywhere.

An opened modal dialog creates an overlay and increments that variable; when you close (or destroy) that dialog the variable will be decremented.

What happens if the dialog is inside an UpdatePanel?
In my test the dialog was built closed (autoOpen=false). Inside the dialog there’s a postback button: it generate a partial reload of the page and only the UpdatePanel will be rendered again.

Some event somewhere calls the .dialog(“open”) and the dialog appears (overlayInstances = 1). Now if we click that postback button, the dialog will be flushed away (not destroyed nor closed!) and the UpdatePanel will be rendered with a new copy of the dialog.
The dialog (again) starts closed but now it will be opened: the .dialog(“open”) is called and overlayInstances++ will be executed.
The $.ui.dialog.overlayInstances isn’t reinitialized, and now its value is (wrongly) 2!.

One final note:
I created another test case: the same page in HTML / javascript, with a postback emulation.
I saw that everything was running clear….until I noticed that I was replacing the UpdatePanel content with a $(“#updatePanel”).html(remoteData).
The .html() funtion is SAFE!! It destroys the inner elements and detach their events. =)
Using a document.getElementById(“updatePanel”).innerHTML = remoteData I saw the overlayInstances problem again.

The fix (updated!) :

I need to keep the balance between “open” and “close” calls to avoid the extra overlay: on every postback button I need to add a js click event that close the dialog. This will forces a _destroyOverlay event that keeps aligned the overlayInstances global value.
Here’s the code:

$('form').on("submit", function () {
  // on EVERY postback the overlay counter will be decremented.
  // if the overlay exists and will be unsafely destroyed (POSTBACK) => ok (because the destructor of the overlay has not been called)
  // if the overlay exists and will be safely destroyed (before POSTBACK) => fails! Please avoid closing dialogs in POSTBACK buttons. It is safe to set the $(settings.popupState).val('0') then postback
  // if the overlay exists and will be safely destroyed (NO POST) => ok (because the "submit" will not be raised)
  // if there's no overlay => it's ok (there's a safeness test on 0)
  if ($.ui.dialog.overlayInstances > 0)
    $.ui.dialog.overlayInstances--; // emulate the dialog closure: very rude, sir
});

This was the old fix...it has some issues:
$('input[type="submit"]', $popup)
  .add('input[type="image"]', $popup)
  .click(function () {
    $popup.dialog('close');
});

If the dialog was opened it is closed before the page load. On page load it will be (re)opened.
If the dialog was closed, it is safe to call an extra close on it.
The dialog is modal, so only inner buttons can raise a postback

 
Leave a comment

Posted by on 2013/08/20 in dev

 

Tags: , , , , ,