Posts

Showing posts with the label pattern

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...

Y U NO use libraries and add stuff

Image
This is an early introduction to a project I have been thinking about for a while. The project is already usable in github but the documentation is lacking all over the place so please be patient and I'll add everything necessary to understand and use yuno . Zero Stress Namespace And Dependencies Resolver Let's face the reality: today there is still no standard way to include dependencies in a script. If we are using a generic JS loader, the aim is to simply download files and eventually wait for one or more dependency in order to be able to use everything we need. The require logic introduced via node.js does not scale in the browser due synchronous nature of the method itself plus the sandbox not that easy to emulate in a browser environment. The AMD concept is kinda OKish but once we load after dependencies, there is no way to implement a new one within the callback unless we are not exporting. I find AMD approach surely the most convenient but still not the best one: w...

ES5 Common Design Patterns Examples - Part 1

// Abstract Factory /* ({}).createInstance() (function (a, b, c) { this.sum = a + b + c; }).createInstance([1, 2, 3]) */ Object.defineProperty( // (C) WebReflection - Mit Style License Object.prototype, "createInstance", { value: (function (create) { return function createInstance(args) { var self = this, isFunction = typeof self == "function", obj = create(isFunction ? self.prototype : self) ; isFunction && args != null && self.apply(obj, args); return obj; }; }(Object.create)) } ); // Abstract Builder /* var person = Object.builder({ setup: function (name) { this.create(); this.instance.name = name; } }); person.setup("WebReflection"); alert(person.instance.name); person.create(); person.instance.name = "Andrea"; alert(person.instance.name); */ Object.defineProperty( // (C) WebReflection - Mit Style License Function.prototype, "builder", { ...

JavaScript Override Patterns

Once we have understood JavaScript Overload Patterns , a good start point to write efficient base classes, it comes natural to wonder about How To Override . First of all, please let me quote one of my favorite sentences from Mr D. I have been writing JavaScript for 8 years now, and I have never once found need to use an uber function. The super idea is fairly important in the classical pattern, but it appears to be unnecessary in the prototypal and functional patterns. I now see my early attempts to support the classical model in JavaScript as a mistake. Douglas Crockford, on Classical Inheritance in JavaScript Override In classical OOP, override means that a sbuclass can declare a method already inherited by its super class, making that method, the only one directly callable for each instance of that subclass. <?php class A { function itsAme() { $this->me = 'WebReflection'; } } class B extends A { function itsAme() { // B instances can acces...

JavaScript Overload Patterns

Update I have continued with patterns into JavaScript Override Patterns . We all know JavaScript does not implement a native methods overload concept and what we usually do on daily basis is to emulate somehow this Classic OOP behavior. There are several ways to do it, all of them with pros and cons, but what is the best way to implement it? A common situation Let's imagine we would like to have a method able to accept different arguments types and return something accordingly with what we received. Usually in Classic OOP an overload cannot redefine the returned type but in JavaScript we can do " whatever we want ", trying to be still consistent, so that we can consider us more lucky than C# or Java guys, as more flexible as well. For this post, the behavior we would like to obtain will be similar to the one we can find in jQuery library, one of the most used, famous, and friendly libraries I know. // create an instance var me = new Person(); // set some property // vi...

Good Old And Common JavaScript Errors

... I won't write any introduction, but I'll let you comment, OK? for loops (plus ++i) for(i = 0; i // global i defined for(var i = 0; i // cache the length if it won't change during the loop // associate once only under certain conditions to speed up for(var i = 0; i // there is absolutely nothing wrong in above loop Few people told me something like: " doode, if you use ++i at the end you need to write i " ... basically the for loop has been rarely understood, let me try again: // directly from C language, 1972 for( // optional inline declaration, coma accepted for more vars ; // optional condition to verify // if undefined, it loops until a break is encountered // this condition is performed BEFORE the first loop // if false, the loop will never be executed ; // optional POST operation, it will never be executed // if the condition is false, "", 0, or null // it is executed in any case AFTER the loop, if any ){}...

PHP or JavaScript implicit Factory method design pattern

Update Above technique could be used to create an implicit Singleton as well. class Demo { // your unbelievable stuff } function Demo($some, $arg){ static $instance; return isset($instance) ? $instance : ($instance = new Demo($some, $arg)); } Demo(1,2)->doStuff(); Demo(1,2) === Demo(1,2); // true from Wikipedia The factory method pattern is an object-oriented design pattern ... More generally, the term factory method is often used to refer to any method whose main purpose is creation of objects. I have talked about JavaScript possibility different times in my prototypal inheritance documentation, and in other posts of this blog. The summary is that thanks to perfect this behaviour , that for some unknown reason someone would like to modify in JS2 , making them ambiguous when you are using a constructor as a function and not, for example, as private method, we can create intelligent constructors that does not require the usage of new keyword - in a Pythonic way: // Java...