Posts

Showing posts with the label JavaScript

Modern Web Development

In the last few years web technology has lived through rapid growth and heavy change. We went from frames to table layouts, to column layouts, to responsive layouts. From html4 to xhtml & flash to html5. From heavy server to rich client. From rpc to soap to rest. From sql to nosql and big data. From MVC to MVP and so on. In the following post i want to describe what has become state-of-the-art from my perspective. A Backend is a REST api  Every backend should be seen as a REST api and every controller as another resource. You want to analyze your problem domain, find your resources and design proper paths for them. They become the M in your MVC Architecture. Developing a webapplication first, and adding an extra REST api later on has to be considered an antipattern. If you do make a REST api, you want to consequently use it yourself, making your frontend its first consumer. This procedure allows you to smoothly add different kinds of clients later on, such as a mobile app or e...

Yet Another Reason To Drop __proto__

I know it might sound boring but I really want to put everything down and laugh, or cry harder, the day TC39 will realize __proto__ was one of the most terrible mistakes. A Simple Dictionary Attack ES6 says that Object.create(null) should not be affected anyhow from Object.prototype . I've already mentioned this in the 5 Reasons You Should Avoid __proto__ post but I forgot to include an example. You can test all this code with Chrome Canary or Firefox/Nightly and the most basic thing you need to know is this: var n = Object.create(null); n.__proto__ = {}; for (var k in n) console.log(k); // __proto__ !!! Object.keys(n); // ["__proto__"] !!! Got it? So, __proto__ is enumerable in some browser, is not in some other but it will be in all future browsers. Let's go on with examples ... // store values grouped by same key function hanldeList(key, value) { if (!(key in n)) { n[key] = []; } n[key].push(value); } // the Dictionary as it is in ES6 var n = Object....

Simulating ES6 Symbols In ES5

Symbols , previously known as Names , are a new way to add real private properties to a generic object. // basic Symbol example var BehindTheScene = (function(){ var symbol = new Symbol; function BehindTheScene(){ this[symbol] = {}; } BehindTheScene.prototype.get = function(k) { return this[symbol][k]; }; BehindTheScene.prototype.set = function(k, v) { return this[symbol][k] = v; }; return BehindTheScene; }()); var obj = new BehindTheScene; obj.set('key', 123); obj.key; // undefined obj.get('key'); // 123 In few words symbol makes possible to attach properties directly without passing through a WeakMap. A similar behavior could be obtained indeed via WeakMaps: // similar WeakMap example var BehindTheScene = (function(){ var wm = new WeakMap; function BehindTheScene(){ wm.set(this, {}); } BehindTheScene.prototype.get = function(k) { return wm.get(this)[k]; }; BehindTheScene.prototype.set = function(k, v) { return wm.get...

5 Reasons You Should Avoid __proto__

Update : when you've done with this post, there's even more in comments and the newer one: Yet Another Reason To Drop __proto__ Too many discussions without real outcome about __proto__ magic evilness or feature. It's time to understand why using it is, today , a bad idea. __proto__ Is NOT Standard (yet) TC39 refused to standardize this property because of the amount of problems it brings . Apparently will be part of ES6 but is not there yet. __proto__ is a silent, non spec'd, agreement. What's the problem? Keep reading ;) __proto__ Could NOT Be There The silent non standard agreement sees __proto__ as configurable property of the Object.prototype . As example, try this in some environment: (this.alert || console.warn)( delete Object.prototype.__proto__ ); // false or true ? The outcome is migrating from false to true . As example, current Chrome has a non configurable descriptor, while Canary has a configurable one. Same is for latest node.js, Firefox, an...

A Cross Platform Inherit Function

This (apparently non working) gist gave me the hint. Stuff I've been dealing with for a while , finally used to bring an Object.create(firstArgOnly) cross platform/engine/client/server code that works. The name? inherit() More Reliable Than Object.create() The reason I didn't even try to polyfill the ES5 Object.create() method is quite easy: it is not possible to shim it in a cross platform way due second argument which requires descriptors features, highly improbable to simulate properly. Even if browsers support the create() method, inherit() guarantee that no second argument will ever be used so we are safe from inconsistencies within the function. Forget hasOwnProperty ! Yeah, one of the coolest things about being able to inherit from null is the fact not even Object.prototype is inherited so we can create real empty objects without worrying about surrounding environment, 3rd parts obtrusive libraries, and the boring and slow obj.hasOwnProperty(key) check. // so...

My Name Is Bound, Method Bound ...

it seems to me the most obvious thing ever but I keep finding here and there these common anti pattern: // 1. The timer Case this.timer = setTimeout( this.doStuff.bind(this), 500 ); // 2. The Listener Case (objOrEl || this).addEventListener( type, this.method.bind(this), false ); What Is Wrong I have explained a while ago what's wrong and how to improve these cases but I understand the code was too scary and the post was too long so here the summary: every setTimeout() call will create a new bound object and this is both redundant and inefficient plus it's not GC friendly there is no way to retrieve that listener created inline so it's impossible to remove the listener any time is necessary ... yes, even after, when you do refactoring 'cause you will need to clean up listeners What You Need The short version is less than a tweet, 64bytes: function b(o,s,t){return(t=this)[s="@"+o]||(t[s]=t[o].bind(t))} This is the equivalent of: // as generic prototy...

JavaScript recent Bits and Bobs

Quick post about few things landed, or not yet, in JavaScript world. preciseTime() In this era loads of +new Date , JSC offers since quite a while a handy global function called preciseTime() . Since this function offers more accuracy than milliseconds, and I am talking about microseconds, which is 1/1000 of a millisecond, it's the best option we have to measure benchmarks or be sure that some time elapsed between two statements in a synchronous code flow. You might don't know that a loop between new Date and another new Date could produce completely unexpected results such a negative integer which is kinda unexpected since zero is the best case we would consider. This behavior is behind ticks and clocks , more or less same reason setTimeout or setInterval have never been accurate in therms of delay. preciseTime , this is the obvious name of my latest git repository, could be shimmed or polyfilled quite easily via a node module I can't npm install for some reason,...

(က) Polpetta, any folder is served spiced

The quick version is: have you ever thought about using node.js to make any folder as a web-server and in a PHPish way where .njs files are required and executed runtime as node modules ? Oh well, I did, and this is the result in Github: polpetta ... enjoy!

The JavaScript typeof Operator Problem

TL;DR don't even try to normalize or shim newer typeof via code: you simply can't! Whenever it was a mistake or not to consider typeof null == "object" , many libraries that tried to normalize this operator failed to understand that null is not the only problem . The JS Polymorphism Nature We can borrow methods for basically everything but primitives values, such booleans, numbers, and strings, do not accept indeed any sort of property or method attached runtime. var s = "hello"; s.greetings = true; alert(s.greetings); // "undefined" However, we can still use methods through call() or apply() : function isGreetings() { return /^(?:ciao|hello|hi)$/.test(this); } alert(isGreetings.call("hello")); // true The only way to find a method in a primitive value is to extend its own constructor.prototype : String.prototype.isGreetings = function () { return /^(?:ciao|hello|hi)$/.test(this); }; alert("hello".isGreetings()); // tru...

Dealing With Future Pointers

Image
I have talked about this already in both JSConfEU and QCon - London and I have also blogged a couple of times about this problem that many developers keep ignoring ... The Unexpected Input In JSConfEU I have showed with my slides this picture: which is simply the reason most of the so called mobile websites won't work as expected. Why that? Because "ontouchend" in window , the most pointless feature detection ever, will produce a positive result and if you decide which event should be attached to the document or any DOM node relying this check, the moment the device that exposes touch events BUT has a trackpad, mouse, or any other alternative pointer device connected, it will fail, it won't work, it will look broken! A Hybrid Solution We could make the assumption that if the user is using fingers, the user will keep using fingers ... while if the user chooses the alternative pointer, there shouldn't be a case where fingers are again on the screen. For this kin...

Ranting About Racing Engines

Update ... regardless this rant is still valid ... I have updated for both Web and node my es6-collections following stricter currently available specs. This is happening right now, or better, since this race started a while ago between alternative browsers and the idea of bringing JavaScript every-bloody-where ... On Engines Fragmentations This happens since ever in vehicles engines and we can all see the difference in themes of both prices and CO2 emissions. Every major car/motorbike engine manufacturer is competing against others. N times the amount of money spent, N times the number of patents slightly different and potentially able to make better engines production slower/farer due patents lifecycle. Almost zero joined effort ... same studies over and over with of course different solutions, and these are always welcome, but rarely a shared effort between teams able to bring the 0 emissions, ecologic and usable engine we are all dreaming about ( look at all these prototypes with...

Asynchronous Storage For All Browsers

I have finally implemented and successfully tested the IndexedDB fallback for Firefox so that now every browser, old or new, should be able to use this interface borrowed from localStorage API but made asynchronous. Asynchronous Key/Value Pairs The main purpose of this asyncStorage API is to store large amount of data as string , including base64 version of images or other files. As it is, usually, values are the bottleneck, RAM consumption speaking, while keys are rarely such big problem. However, while keys are retrieved asynchronously and in a non-blocking way, but kept in memory, respective values are always retrieved asynchronously in order to do not fill the available amount of RAM for our Web Application. Database Creation/Connection Nothing more than ... asyncStorage.create("my_db_name", function (db, numberOfItems) { // do stuff with the asyncStorage }); Storing An Item As it is for localStorage, but async asyncStorage.create("my_db_name", function (d...

Working With Queues

Programming with queues is basically what we do in any case: it does not matter if we write code in that way, we simply think in that way. This means that our logic flow is generally distributed in tasks where "on case X" we apply "logic/procedure Y" .. isn't it? The Good'ol GOTO The goto statement has been historically criticized, as well as the switch one, and in both cases is about entry and exit points in a generic workflow. Nowadays, we can say the GOTO is not needed anymore thanks to functions, where rather than thinking " when this case occurs, goto this instruction " we call the required function in charge of that specific task providing arguments or context as we go. We may then agree that GOTO is not really a must have while functions are, with all the power and flexibility we might need, and specially in JavaScript. On Block-Scope JavaScript has theoretically no block-scope concept, at least until very latest versions of ECMAScript whe...

Graceful Migration From ES3 to ES5

Just slides I have showed today here @ nokia for a tech talk, hope you'll enjoy them, cheers Update Here you can find the updated version of the Object.forEach proposal: gist 2294934 Main changes are about some inconsistent behavior in Safari, not it should work without problems. Thanks to @medikoo for his hint. ... rock'n'roll ...

On Obtrusive Polyfills

Image
I'll try to make the point short and simple, starting with the tl;dr version: if you create a polyfill and during features detection you realize this cannot work, drop it and let other libs deal with it. Broken Object.defineProperty This is just one case really annoying. Bear in mind I am not talking about " making perfect polyfills ", this is almost impossible most of the case, I am talking about broken runtime even if you did not really do anything that special. It was the case of Object.defineProperty shimmed through es5-shim code ... this library is good but that method, as many others, are simply broken. I was trying to add a setter/getter in IE < 9 and shit happened, more specifically a thrown exception happened ... the repository itself explains that this method and others should fail silently ... so it's OK for the developer to know about it and avoid trusting these methods ... This Is Not OK If I check if Object.defineProperty is there and this is al...

A Tweet Sized Queue System

The Code This is the 138 bytes version: function Queue(args, f) { setTimeout(args.next = function next() { return (f = args.shift()) ? !!f(args) || !0 : !1; }, 0); return args; } While this is the 96 one: function Queue(a,b){setTimeout(a.next=function(){return(b=a.shift())?!!b(a)||!0:!1},0);return a} The Why In almost every QCon London talk I have heard the word asynchronous . Well, the aim of the tweet sized function I have just written above is to make things easier. After I have implemented builder/JSBuilder.js for wru , so that Python is not needed anymore to build the tiny library, I needed to make builder/build.js usable in a way that asynchronous calls through node won't bother, at least visually, the normal flow of the script. After that I have thought: " why not making a generic Queue function with Promises like approach " ? The What It's quite straight forward, you create a queue, you use the queue. You might eventually pollute the queue or chang...

I Heard You Like To Write Less

Update apparently this proposal is being considered in es-discuss ... not the implicit return so far but the " redundant " function keyword. This is last draft from Brendan Eich: FunctionDeclaration: function Identifier ( FormalParameterList_opt ) { FunctionBody } Identifier ( FormalParameterList_opt ) [no LineTerminator here] { FunctionBody } ShortFunctionExpression: Identifier_opt ( FormalParameterList_opt ) [no LineTerminator here] { FunctionBody } Identifier_opt ( FormalParameterList_opt ) => InitialValue I'm @qconlondon waiting for the next talk so I decided to take a couple of minutes to blog about this little experiment. In ES-Discuss developers are still talking about function keyword, if it's needed or not. I believe the fact CoffeeScript has no explicit function is one of the major reasons devs have been attracted so I made it even simpler. Just Drop The Function With current ES 3, 5, or 5.1 syntax I can't really see problems or ambigui...

JavaScript Test Framewors: more than 30 + 1

After @szafranek hint and suggestion, wru landed almost at the end of this Wikipedia List of unit testing frameworks page. If you use this tweet size hand made imperfect script in the wikipedia page console: a=q="querySelectorAll",[].map.call(document[q](".mw-headline,.wikitable"),function(v,i){i%2?a=v.textContent:o[a]=v[q]("tr").length},o={}),o You gonna see that JavaScript is third when it comes to number of test frameworks ... and not sure that's good, anyway, here a quick description of mine. About wru You can find most info in github page itself but essentially wru is a generic purpose, environment agnostic, JavaScript tests framework compatible with both client and server, where client means every bloody browser, and server means Rhino, node.js, and recently phantom.js too. To be really fair, wru is not exactly a unit test framework since it does not provide by default anything related to mocks or stubs. However, wru is so tiny and unobtru...

If You Don't Get It, Go And Get It!

Oh well, a rant against another one ... how lovely is this? Just trying to make your week end, right? I am talking about this misleading post with indeed 29530+ views and just 1 Favorited entry (right now) that must be the post author itself since I can't even check and click that red link ... anyway ... At the very beginning I thought that was a sarcastic post .. like, the opposite of reality, then I have realized it wasn't ... or was it? V8 is not server-class ? Define "server class programming language" first ... 'cause I have tried to search it in Google (with quotes) and result was like a single entry that indeed pointed to some Java stuff ... This argument is kinda boring in 2012, specially against a general purpose programming language as JS is, you don't say? I mean, doooooode, should I remind you the Java Applet joke early in the Web era? So it was fine for a server-class programming language to do client side stuff? Or it's just a matter of ...