Skip to content

Instantly share code, notes, and snippets.

@matthewstokeley
Last active April 29, 2020 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewstokeley/78283bb51af41f0cdc78dcd9e23fe79a to your computer and use it in GitHub Desktop.
Save matthewstokeley/78283bb51af41f0cdc78dcd9e23fe79a to your computer and use it in GitHub Desktop.
data model writeup

The data model for data-binding

Data models contain the entirety of application state (from the elm-lang guide - "The point of the model is to capture all the details about your application as data." )

An Object Literal

A model could be as simple as a plain javascript object


const model = {}

A functional data model

Elm-style data models encourage easy data binding


// @todo make enterprise ready

const msg = ( fn ) => {}

// data model pattern based on an elm-style mvu 
const model = {

	loading: function( msg ) {
		return msg( () => {
			return

		} )
	},
	failure: function( msg ) {
		return msg( () => {
			return
		} )
	},
	success: function( msg ) {
		return msg( () => {
			return

		} )
	}
}


const view = ( model, msg ) => {

	switch msg.status
		case 'loading'
		model.loading( msg )

		break

		case 'failure'
		model.failure( msg )

		break

		case 'success'
		model.success( msg )

		break

}

Other data-binding patterns with data models

Discrete event payloads and functional composition are not central to the data model pattern.

This data model is created inside an IIFE and event logic is abstracted away. We're a state machine and several steps away from inventing a reactive system.

// @todo make enterprise ready



const model = ( function() {

	let dataModel = {
		count: 0
	}

	const modelEvents = function( dataModel ) { 
		return {
			counter: function( _ ) { ++dataModel.count }
		}
	}

	return modelEvents( dataModel )

} )()
<div id="div" data-counter="0"></div>

Now we can easily poc two-way data-binding on the dataset attribute.

function view( model ) {

	let _el = document.getElementById('div')

	let _clonedEl = _el.cloneNode( true )

	for ( let prop of model ) {
	
		if (model.hasOwnProperty ( prop ) {

			_el.addEventListener( 'click', () => {
				_clonedEl.dataset[ model[ prop ] ] = model[ prop ]( _el.dataset[ model[ prop ] ] )
			})
		
		}

	}

	return _clonedEl

}

@matthewstokeley
Copy link
Author

no side effects!

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