Skip to content

Instantly share code, notes, and snippets.

@Goopil
Created November 30, 2016 19:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Goopil/b4c40cd9a509237cb388f3e9e33d68f8 to your computer and use it in GitHub Desktop.
Save Goopil/b4c40cd9a509237cb388f3e9e33d68f8 to your computer and use it in GitHub Desktop.
map Mappers & and collections from js-data datastore to vue instance
<template>
...
</template>
<script>
import { mapCollections, mapMappers } from './plugins/jsData'
export default {
name: 'app',
computed () {
...mapCollections([
'user'
]),
...mapMappers([
'User'
])
}
}
</script>
import Vue from 'vue'
import App from './App.vue'
import { DataStore } from 'js-data'
import jsDataPlugin from './plugins/jsData'
const Dstore = new DataStore()
Dstore.defineMapper('user')
Vue.use(jsDataPlugin)
new Vue({
el: '#app',
template: '<App/>',
components: { App },
DStore
})
class JsDataVuePlugin {
constructor () {
this.defaults = {
computedName: 'dstore',
storeName: 'Dstore'
}
this.storeName = ''
this.computedName = ''
}
/**
*
* @param Vue
* @param options { computedName, storeName }
* @returns {*}
*/
install (Vue, options = {}) {
this.computedName = '$' + (options.computedName || this.defaults.computedName)
const storeName = this.storeName = options.storeName || this.defaults.storeName
Vue.mixin({
computed: {
[this.computedName]: {
cache: false,
get () {
return this.$root.$options[storeName]
}
}
}
})
}
}
const plugin = new JsDataVuePlugin()
export default plugin
/**
* map collections to computed props
* @param collectionNames
* @returns {Array}
*/
export const mapCollections = function (collectionNames) {
const computeds = {}
collectionNames.forEach(name => {
computeds[name] = {
cache: false,
get () {
const collection = this[plugin.computedName].getCollection(name)
collection.on('destroy', () => { this.$forceReload() })
collection.on('remove', () => { this.$forceReload() })
return collection.filter()
}
}
})
return computeds
}
/**
* @param mapperNames
* @returns {{}}
*/
export const mapMappers = function (mapperNames) {
const computeds = {}
mapperNames.forEach(name => {
computeds[ucFirst(name)] = {
cache: false,
get () { return this[plugin.computedName].getMapper(name.toLowerCase()) }
}
})
return computeds
}
/**
*
* @param str
* @returns {string}
*/
function ucFirst (str) {
console.log(str)
const lower = str.toLowerCase()
return lower.replace(/(^| )(\w)/g, function (x) {
return x.toUpperCase()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment