Skip to content

Instantly share code, notes, and snippets.

@carlmw
Created October 8, 2014 15:38
Show Gist options
  • Save carlmw/9c0c59119c206f5219fa to your computer and use it in GitHub Desktop.
Save carlmw/9c0c59119c206f5219fa to your computer and use it in GitHub Desktop.
function WidgetConfig() {}
WidgetConfig.prototype.__fields__ = [];
WidgetConfig.addFields = function (newFields) {
var Super = this;
function Child() {
return Super.apply(this, arguments);
}
_.extend(Child, Super);
Child.prototype = Object.create(Super.prototype);
Child.prototype.__fields__ = Super.prototype.__fields__.concat(newFields)
return Child;
}
@carlmw
Copy link
Author

carlmw commented Oct 8, 2014

It means we can construct our classes once and instantiate them many times.

@romain-h
Copy link

romain-h commented Oct 8, 2014

Your addFields() is like an extend method. But then if I need to tweak a result for example for Highchart should I return like this:

var PollingHighchartWidgetConfig = CustomWidgetConfig
.addFields([HIGHCHART_DATA_FEED_URL, API_KEY_FIELD, API_TOKEN_FIELD]);

PollingHighChartWidgetConfig.prototype.changeUrl = function() {
      var idx = _.findIndex(this.fields, { name: 'url' });
      this.fields[idx] = HIGHCHART_FORMAT_FIELD;
}

// Instantiation
var config = PollingHighChartWidgetConfig();
config.changeUrl();

?

@carlmw
Copy link
Author

carlmw commented Oct 8, 2014

Just start a new inheritance chain.

var CustomWidgetConfig = WidgetConfig
.addFields([FORMAT_FIELD, DATA_FEED_URL]);
var PollingCustomWidgetConfig = CustomWidgetConfig
.addFields(POLLING_FIELDS);

var HighchartWidgetConfig = WidgetConfig
.addFields([HIGHCHART_DATA_FEED_URL]);
var PollingHighchartWidgetConfig = HighChartWidgetConfig
.addFields(POLLING_FIELDS)

// Etc...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment