D3 Component Data Model

This post expands on the previous post: Improvements to D3 Resuable Component Pattern


I recently had this situation where a JSON Array needed to be populated by two instances of the same D3 component that I had built, at virtually the same time, using two different datasets.

The array was then further processed by two instances of another of my D3 components that manipulated the data differently based on the dataset.

I had two scopes to deal with, the first scope included the first instance of the first component and the first instance of the second component and the second scope included the second instance of the first component and the second instance of the second component.

Using locally defined data structures and an event bus (with channel as scope) to both orchestrate execution across components as well as transfer data structures between components (in event details) in a de-coupled way is one way of doing it, but it’s helpful when debugging an app to have your “global” data structures in one place so you can inspect their content from anywhere. Another way, which is is simpler from a framework-code-size and maintenance point, is having a “model” component that is exposed to all components where the components may declare a scope.

D3 is needed to run the code below but you may redefine the model on its own and use without D3.

// extensions object on d3
    d3.ext = {};

    // this creates automatic getter/setter on the returned object for each public property
    // so that public properties can be accessed as componentInstance.property(value) (when setting)
    // and componentInstance.property() (when getting)
    function getterSetter(obj)  {

       if (obj.props.scope)
            throw new Error("scope should be configured outside of component")

      // place holder for scope getter/setter
       obj.props.scope = undefined;

       for (o in obj.props) {
            obj[o] =  new Function("value", "if (!arguments.length) return typeof this.props['" + o +
            "'] == 'function' ? this.props['" + o + "'].call(this) : this.props['" + o + "'];" +
            "this.props['" + o + "'] = (typeof value == 'function' ? value.call(this) : value); return this")


        // Component Data model
    // use model.create("scope", {property: value, property: value, etc}) to create new properties
    // use model.propertyName("scope") to get the value for a property in the given scope
    // use model.propertyName("scope", value) to set the value for a property in the given scope
    // use console.log(model.entries()) to view all entries for all components
    // setters are chain-able
    // the scope is usually the component's .context() but can be any other id

    d3.ext.model = function() {

        var obj = {}

        obj.entries = function() { return obj}

        obj.create = function(scope, json) {

            if (scope === undefined)
                throw new Error("scope property not configured").stack

            obj[scope] = obj[scope] || {}

            obj[scope].props = obj[scope].props || {}

            for (key in json) {
                obj[scope].props[key] = json[key]

            for (o in obj[scope].props) {
                if (obj[scope].props.hasOwnProperty(o)) {
                    obj[o] =  new Function("scope, value", "if (!scope) return; if (!value) " +
                        "return this[scope].props['" + o + "'];" +
                        "this[scope].props['" + o +
                        "'] = value; return this")
            return obj;
        return obj;


    var model = d3.ext.model()

    // create component
	var myChart = function chart(model) {

		// private vars defined ordinarily
		var a, b, c, d, etc;

		// let's refer to the instance as obj
		var obj = {};

		// place to hold publicly accessible properties
		obj.props = {};

		// all publicly accessible properties are defined here

		obj.props.area = function() {
			return this.props.height *  this.props.width

		obj.props.someArray = [];

		obj.props.test = function() {
			return Math.random()

		// create getters/setters

		// this is how private methods are defined
		var somePrivateMethod = function() { console.log('hi, i am a private method')}

		// this is how public methods are defined...
		obj.render = function() {

			// generate chart here, using `obj.props.width` and `obj.props.height`

			console.log('rendering chart with width = ' + obj.props.width +  ' and height = ' + obj.props.height)

			if (model) console.log('scoped global var:', JSON.stringify(model.testValue(obj.scope())))

			return obj;

		return obj;

    // testing the original settings
	console.log(myChart().width(), myChart().height())

    model.create("A", {testValue: {a: 10, b: 20, c: 30}})
    model.create("B", {testValue: {a: 100, b: 200, c: 300}})

	// create new instances with new settings
	var chart1 = myChart(model)


	var chart2 =  myChart(model)
	// example of rendering after setting

	var chart3 = myChart(model)
			// example of function as value generator
			.height(function() {return this.width() * 4})

	var chart4 = myChart(model)

	// testing the new settings
	console.log(chart1.width(), chart1.height())
	console.log(chart2.width(), chart2.height())
	console.log(chart3.width(), chart3.height())

	// set a new width for chart3

	console.log(chart3.width(), chart3.height())

	console.log(chart4.width(), chart4.height())

	// tests for function reference as value for setter

	// test getter for property
	console.log('area property with default function', chart1.area())

	// set property to function reference via closure (use only a function reference if assigning by value)
	// else use two as shown
	chart1.area(function() {return function() { return Math.pow(this.width(), 2) * (Math.PI/4)}})

	// test getter after change
	console.log('area property for chart1 with updated function', chart1.area())

	console.log('area property for chart1 with updated function after width is changed', chart1.width(700).area())

	console.log('area property for chart2 with original function', chart2.area())

        // test assigning a closure to a property
	function testClosure() {
		var someFunction = function() {
			return ~~(Math.random() * 1000);
		return function() {
			return someFunction();



	// using typed properties
	chart1.someArray().push(5) // or chart1.someArray([1,2,3])


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s