Delegate Prototypes – Say What!?!



Delegate Prototypes – Say What!?!

0 0


sdjs-delegate-prototypes

My slides for a lightning talk at SDJS on JavaScript delegate prototypes

On Github shrunyan / sdjs-delegate-prototypes

Delegate Prototypes

Say What!?!

Created by @stuartrunyan

What are we going to do?

  • Define what will be our delegate prototype.
  • Use a factory to generate object instances.
  • Demonstrate usage.

* p.s. I'll be using ES6 syntax

Store.js

// exports ES6 module
export default {
  get(key) {
    return this[key]
  },
  set(key, val) {
    this[key] = val
    return this[key]
  }
}

* Bonus points: Wrap your store in an observable

TimeStore.js

import Store from './Store'

function TimeStore () {
  // Object.assign concats our objects together
  // Object.create sets Store as prototype of new object
  return Object.assign(Object.create(Store), {
    isSet(key) {
      return this[key] ? true : false
    },
    getEpoch(key) {
      return new Date(this.get(key)).getTime()
    }
  })
}

export default TimeStore
  • Object.assign: This is the same as `_.extend()` or `$.extend()`
  • Object.assign is a new ES2015 feature and must be [polyfilled][1]
  • Object.create: ES5

app.js

import TimeStore from './TimeStore'

const store = TimeStore()

store.isSet('currentTime') // false
store.set('currentTime', Date()) // timestamp
store.isSet('currentTime') // true
store.get('currentTime') // timestamp
store.getEpoch('currentTime') // timestamp
  • Babel Repl
  • Show prototype chain in devtools
  • Factory allowed use of object with out `new` keyword
  • Import transpiliation issue. It's a reference, not immutable bindings. @see http://www.2ality.com/2015/07/es6-module-exports.html

So what... Why do I care?

  • Shared Functionality
  • Smaller Interface to Test
  • Simple OLOO code

shout outs to...

Code syntax highlighting courtesy of highlight.js.

  • If interested in more information checkout articles from these people.

Questions?

Delegate Prototypes Say What!?! Created by @stuartrunyan