BBC-News/Imager.js — pull request #22 by oncletom (2013-10-30 09:27:17+00:00)
Title: [PROPOSAL] Constructor API

# The intention

Actual implementation of Imager registers events on the go and trigger image replacement immediately. *IMO the constructor is doing too much things [you can't replay later without calling numerous functions](https://github.com/BBC-News/Imager.js/blob/master/Imager.js#L73-81)*.

It also ships it own version of `$`. *Every decent project including Imager might already have solved this problem (by including jQuery or something else)*.

# The proposal

## Explicit Elements Argument

By providing them with a pure DOM selection:

```javascript
var els = document.getElementById('main').getElementsByClassName('delayed-image-load');
var imgr = new Imager(els);
```

By providing them from your own library:

```javascript
var imgr = new Imager($('#main .delayed-image-load'));
```

For simplicity sake, a string selector can be provided, then using `querySelectorAll` internally:

```javascript
var imgr = new Imager('#main .delayed-image-load');
```

## Factory

The constructor instantiate the Imager instance while the factory instantiate and processes elements. We could have two possible syntax, each has its own pros and cons.

### without `new`

```javascript
var imgr = Imager('.delayed-image-load');

// equals to
// var imgr = new Imager('.delayed-image-load');
// img.changeDivsToEmptyImages();
// img.init();
// img.shallIDelayImageReplacement();
```

**pros**:
* no new static method name to remember
* shortest way of writing possible
* if you don't want the one liner way, you can fine tune it the way you want

**cons**:
* possibly confusing to remember which of `new Imager()` or `Imager()` I should use
* not very common pattern among JS projects so it might even be not so natural to use

### `create` static method

```javascript
var imgr = Imager.create('.delayed-image-load');

// equals to
// var imgr = new Imager('.delayed-image-load');
// img.changeDivsToEmptyImages();
// img.init();
// img.shallIDelayImageReplacement();
```

**pros**:
* explicitly different from the constructor
* if you don't want the one liner way, you can fine tune it the way you want
* [people won't forget the `new` word and mess up the `this` context of Imager](http://ericleads.com/2012/09/stop-using-constructor-functions-in-javascript/)

**cons**:
* [constructor vs factory debate really](http://ericleads.com/2013/01/javascript-constructor-functions-vs-factory-functions/)