Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • About me
Home
About me
  • Nikola Brežnjak blog
  • Home
  • About me
JavaScript

JavaScript event loop video explanation

Awesome short video about JavaScript event loop

One cool thing I didn’t know is that you can defer something right after the end of the stack. So for example the code below in the setTimeout function would print to console “done”, right after “hi” and “testing”:

console.log("hi");

setTimeout(function(){
    console.log("done");
}, 0);

console.log("testing");

 

JavaScript

Converting a JavaScript switch statement into a function lookup

I just read a great post on WebTools Weekly newsletter about how to convert a JavaScript switch statement into a function lookup. Here’s the full content from there, so be sure to check it out if you like it (it’s one newsletter a week, and no – I’m not affiliated with them in any way).

Because of the problems inherent in using JavaScript’s switch statement, many developers and reference guides will recommend avoiding switch constructs and instead using something called amethod lookup (also referred to as a lookup table or even dispatch table). Let’s convert a switchstatement to a method lookup, so we can see how this is done. Here’s our switch:

function doSomething(condition) {
  switch (condition) {
    case 'one':
      return 'one';
    break;

    case 'two':
      return 'two';
    break;

    case 'three':
      return 'three';
    break;

    default:
      return 'default';
    break;
  }
}

(JS Bin example)

All of this is inside a doSomething() function, with a condition passed in. The possible values are ‘cased’, to define the return value. This is cleaner than a messy if-else construct, but can we clean it up even more? Here’s basically the same thing in the form of a method lookup:

function doSomething (condition) {
  var stuff = {
    'one': function () {
      return 'one';
    },

    'two': function () {
      return 'two';
    },

    'three': function () {
      return 'three';
    }
  };

  if (typeof stuff[condition] !== 'function') {
    return 'default';
  }


  return stuff[condition]();
}

(JS Bin example)

In the demo, you can see four logs in the console, one for each valid condition and then another one to demonstrate the default condition when the argument doesn’t match one of the methods.

You can see why people like this technique. It’s clean, elegant, and seems a little more sophisticated without being more complex. I’ve only scratched the surface on this, so here are a few good resources to read up more on this subject:

  • Don’t Use Switch in Programming JavaScript Applications by Eric Elliot.
  • Using Dispatch Tables to Avoid Conditionals in JavaScript by Josh Clanton
Stack Overflow

Is there an event just before the radio button is about the be checked?

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

This is the part of the code for one of the radio buttons:

$("#new").click(function(){
    if( $('#new').is(':checked') )
        $.jGrowl("You already have this option selected!", life: 1500});
    else
        changeOption(1);
});

Now, I understand that the else part will never run, because the radio button will be already checked on click event. What I’m wondering is, is there an event which would let me capture the state of the radio button (which is about to be clicked) and therefor determine if he is not yet clicked, and if so change the option to this newly selected one.

The answer, by JOPLOmacedo, was:

Use the mouseup event instead.

$("#new").mouseup(function(){if( $('#new').is(':checked'))
        $.jGrowl("You already have this option selected!", life:1500});else
        changeOption(1);});

The fiddle.

Edit
Even though the mouseup event works, it seems more logical to use the mousedown event. Here’s that fiddle.

Miscellaneou$

Ekobit DevArena 2014

Here are my notes (on Croatian) from the DevArena 2014 hosted by Ekobit. The bolded bullet points were, you guessed it, topics. All in all, a very well organised developers conference.

  • Otvoreno o softerskom inženjerstvu i profesionalizmu
    • Leveli
      • level 0: continuous integration, unit testing
      • level 1: TDD, refactoring
      • level 2: coding standards
    • Testing stuff
      • https://github.com/Moq/moq4 – mocking library for .NET
      • Unit testing FTW!
      • http://sandcastle.codeplex.com/ – doxi iz unit testova; New => Help Project
      • Ne diraj ako nema testova, osim Right click => Extract to Method in VS
      • CodeRush & ReSharper
      • Code Contracts
  • Application insights
    • za sad jos samo u preview modu i samo za web http://stackoverflow.com/questions/26099664/vs2013-application-insight-for-desktop-applications/26544013#26544013
    • ALM – application lifecycle management
    • omogucava provjeru dostupnosti, performansi, koristenja
    • cilj: smanjiti MTTD (mean time to detect) errora
    • servis se obavezno vrti na Azureu
    • Add New project => Web performance and load Test project
    • log4net nugget + insights appender
    • Visual studio online
    • Azure is the way to go!
  • PRISM
    • instalacija preko NuGet-a
    • poznat još https://cinch.codeplex.com/, ali je kao jednostavniji, dok Prism (kompleksniji) im je jako se dobro uklopio u to dok su morali napraviti samo neki dio aplikacije da bude naplatni
    • napravljen po TDD i postoji source code
    • https://unity.codeplex.com/ i http://msdn.microsoft.com/en-us/library/dd460648(v=vs.110).aspx => bootstraping
    • prism inace ima sljedece patterne
      • addapter
      • app controller
      • command
      • composite and composite view
      • DI
      • IOC
      • Event aggregator
      • Facade
      • Observer
      • MVVM
      • Registry
      • Repository
  • Razvoj web i mobilnih multimedijskih aplikacija na HTML 5 platformi
    • http://middle-earth.the-hobbit.com, https://github.com/mbostock/d3/wiki/gallery
    • web browser će postati OS
    • video, audio tag
    • Grafika na webu:
      • Canvas
        • samo elementarno, requestTimeFrame
        • problem skaliranja slike
      • SVG
        • skaliranje slika
        • svaki element moze imati neki filter, npr. blur
        • ima animacije (<set>, <animate>)
        • IE 10 ima probleme s animacijama
      • ChartJS, CanvasJS, EASEJS, Fabric, Paper, Processing, Kinetic, JustGauge, $.plot chart
      • WebGL
        • grana OpenGL-a
        • direktan pristup GPU – high performance, but compli freakin cated
        • https://github.com/begedin/DiceAndRoll – PHASER!
  • Što je novo u XAML-u i XAML alatima za Visual Studio
    • NIŠTA
    • CPU usage tool with support for WPF (update 2 u VS2013)
    • .NET Managed Memory Analyzer
  • IoC i DI
    • Inversion of Control
    • Dependency Injection
    • Unity IOC, Windsor, Structure Map, nInject
    • AOP – aspect oriented programming
Stack Overflow

WebBrowser control that can handle HTTPS

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

I am searching for a substitute of the WebBrowser control in .NET which can handle HTTPS. This question is similar here on Stack Overflow, but none of these controls offer HTTPS.

btw, just to mention, I tried all these

GeckoFx – development stopped
Se7en – this is actually continued GeckoFx
Webkitdotnet – no one replying on forum

but none of them support HTTPS, so I’m kind of stuck here :/.

Also, to mention, WebBrowser control that comes with .NET framework works just fine with HTTPS, but the reason I can’t use it is because my app uses a lot of javascript that IE refuses to render, and for example Firefox (gecko engine) or Chrome (webkit) work just fine.

So, please if someone knows a good control that can do this (can be Webkit or Gecko wrapper, it doesn’t mind, as long as it’s not an IE wrapper).

This one I answered myself:

After long googling I finally ended up using the same as I was using before. So Webkit fromhttp://sourceforge.net/projects/webkitdotnet and I ended up purchasing a SSL certificate for my domain and now all is fine.

Stack Overflow

What is the difference between $(window) and window in jquery/javascript

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

What is the difference between javascript window and jquery $(window)?

I tried in the Chrome console and I get this: enter image description here

So, I would conclude is “just” a window object wrapped in a jquery object in a way that then I can use jquery’s functions on it (like height(), width(), etc…)

The answer, by user Elias Van Ootegem was:

When you write $(window), you should know that that piece of code is going to run on the JS engine. Ever why jQ objects all have parentheses around them? Simple because $ is a function object. Basically you’re calling the $ function, and passing the native global, or window object to it as an argument.

If you browse through the jQ source code, you’ll see that it’ll pass that object on to many internal functions and in the end, it’ll return a jQ wrapper object.
So yes, your assumptions are pretty much correct.

Miscellaneou$

Love you Apple but hasn’t this gone too far?

Love you Apple, I really do, but this video is just too true! Since you’ve allowed that I install iOS8 on my beloved 4S (unfortunately the best and last normal sized phone you’ve made [I know it’s not your fault, it’s what market demands, but still it “feels” wrong]) I have all but good words for it. Slow this, slow that, apps crash which never before crashed, the list goes on… Sure, I understand, my phone is 3 years old so what you’re (subtly) saying is that I should update. But why should I, if I’m perfectly fine with this one (and Androids just don’t resonate with me) go and buy a new one? That being said I think you should really allow us (and yes, there is more of us) to downgrade to iOS7.

There, my 0.02$.

IDIOTS from BLR_VFX on Vimeo.

Stack Overflow

tmhOauth twitter api stopped working with update_with_media call

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

So, this morning I got the following error:

{"errors": [{"message": "The Twitter REST API v1 will soon stop functioning. 
Please migrate to API v1.1. https://dev.twitter.com/docs/api/1.1/overview.",
"code": 68}]}

Since I was using the tmhOauth twitter api I went to look if there are updates for it, and as it seems there is an issue listed here.

I’m using the api to update the status with media like this:

$code = $tmhOAuth->request('POST', 'https://upload.twitter.com/1/statuses/update_with_media.json',
        array(
            'media[]'  => "@{$image}",
            'status'   => "{$text}"
        ),
        true, // use auth
        true  // multipart
);

I found notes that I should just change the link to use 1.1 instead of 1 but it’s still not working.

I actually answered this one my self after finding the solution:

My main problem was that I didn’t read the docs fully! While the change in the url from 1 to 1.1 was sufficient I missed the point by not looking that the new url for update_with_media, as explained in thedocumentation, is https://api.twitter.com/1.1/statuses/update_with_media.json, namely it’s api instead of the old upload subdomain.

So, now my api call looks like this and all works again:

$code = $tmhOAuth->request('POST', 'https://api.twitter.com/1.1/statuses/update_with_media.json',
        array(
            'media[]'  => "@{$image}",
            'status'   => "{$text}"
        ),
        true, // use auth
        true  // multipart
    );

Hope this helps someone.

Stack Overflow

How to detect the item has been dropped in the same sortable list in jQuery UI

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

I have two connected sortable lists. My code works fine for when I drag one element from the list on the left side to the one on the right side, but can you tell me what event should I be looking for if I want to know the order of items in the left list when an item gets dragged and dropped in the same list (basically reorder the items in the same list, not dragging and dropping to the other list but to the same).

Here is the link to the code: http://jsfiddle.net/Hitman666/WEa3g/1/

So, as you will see I have an alert when items are dragged and dropped in oposite lists, but I need an event also for when the list (for example the green one) gets reordered. Then I would need to alert the order, for example: 4,3,2,1

HTML:

<ul id="sortable1" class="connectedSortable">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>

<ul id="sortable2" class="connectedSortable">
    <li>Item 5</li>    
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>    
</ul>

CSS:

#sortable1, #sortable2 { list-style-type: none; margin: 0; padding: 0; float: left; margin-right: 10px; }#sortable1 li, #sortable2 li { margin: 0 5px 5px 5px; padding: 5px; font-size: 1.2em; width: 120px; }#sortable1 li{background: green;}#sortable2 li{background: yellow;}

JavaScript:

$(function() {
    $("#sortable1, #sortable2").sortable({
        connectWith: ".connectedSortable",
        receive: myFunc
    }).disableSelection();

    function myFunc(event, ui) {
        alert(ui.item.html());
    }
});

 

The answer, by user yoelp was:

You need to use the update event. Here is my example (notice that I made 2 extra function calls to sort since you needed the evt only on the left list):

$(function(){
    $( "#sortable1" ).sortable({
        connectWith: ".connectedSortable",
        update: myFunc
    }).disableSelection();

    $( "#sortable2" ).sortable({
        connectWith: ".connectedSortable",  // deactivate:myFunc
    }).disableSelection();

    function myFunc(event, ui){
        var b = $("#sortable1 li"); // array of sorted elems
        for (var i = 0, a = ""; i < b.length; i++)
        {
            var j=i+1; // an increasing num.
            a = a + j + ") " + $(b[i]).html() + '\n ' //putting together the items in order
        }
        alert(a)                 
    }
});
Stack Overflow

PHP memory_get_peak_usage and ini_set(‘memory_limit’, ‘-1’)

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

I recently ran into memory allocation problems, so I started experimenting with the ini_set('memory_limit', value); directive where I tried to enter values incrementaly. Now, searching through the web (and SO) I found out that I can put -1 as the value. So, I did and now the script runs fully to the end without breaking (before I used to get the memory allocation error).

What I don’t understand, however, is that given these two lines at the end of the script’s file:

$mem = memory_get_peak_usage(true);         
echo "Peak mem. usage: <b>". round($mem /1024/10124,2)."</b> MB";

produce around 10.8MB and when I look into the /var/log/messages I can see this line:

Nov2113:52:26 mail suhosin[1153]: ALERT-SIMULATION - script tried to increase  
memory_limit to 4294967295 bytes which is above the allowed value (attacker  
'xx.xxx.xxx.xxx', file '/var/www/html/file.php', line 5)

which means the script tried to alocate 4096MB!

How can this be? And also, what interest me the most is why didn’t the script execution stop in this case? Is it because of the ini_set('memory_limit', '-1');? I mean, I did read that putting -1 as the valueis not recomended and I know where the problem lies in the script (reading too big amount of data at once in the memory), and I will go and fix it with sequential reading, but I’m just baffled about these data differences, so I would be gratefull if someone can shed some light on it.

The answer, by user Sverri M. Olsen was:

It is because the suhosin patch uses its own “hard” maximum memory limit, suhosin.memory_limit.

From the configuration reference:

Suhosin […] disallows setting the memory_limit to a value greater than the one the script started with, when this option is left at 0.

In other words, if you change the memory_limit so that it is bigger than suhosin’s upper limit then it will simply assume that you are an “attacker” trying to do something suspicious

Page 46 of 53« First...102030«45464748»50...Last »

Recent posts

  • Productivity tip: rate things 1-10 without 7
  • Productivity: Paper, Pomodoro, Kanban, Tracking, and actually showing up
  • The Keyboard Layout That’s Making Us Type Slower
  • Stop Tabbing. Start Using Your Monitor
  • StackOverflow – Was It Worth It?

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (36)
  • Daily Thoughts (78)
  • DevThink (2)
  • Go (3)
  • iOS (5)
  • JavaScript (128)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (3)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (83)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (44)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (82)
  • Unity3D (9)
  • VibeCoding (2)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak