如何在不同的JavaScript / Parse对象之间共享方法?

时间:2016-01-23 08:20:04

标签: javascript parse-platform ecmascript-6

此文件定义Document对象的保存/查找方法并将其导出:

商品/ document.js

import Parse from 'parse'
import _ from 'lodash'

Parse.initialize('APP_ID', 'CLIENT_ID')

const Document = {}
const ParseDocument = Parse.Object.extend('Document')

Document.save = (json) => {
  const document = new ParseDocument()
  return document.save(json)
}

Document.find = () => {
  const query = new Parse.Query(ParseDocument)
  return query.find().then((results) =>
    _.map(results, (result) =>
      result.toJSON()
    )
  )
}

export default Document

此文件使用导出的方法:

视图/ documents.js

submit () {
  const document = {
    title: this.title,
    content: this.content
  }
  Document.save(document).then(() =>
    Document.find().then((result) => /* DO STUFF */)
  )
}

如果我只有一个对象,这很好。问题是,我有很多。例如,我也有一个Section对象。

如果我遵循这种模式,我将不得不这样做:

商品/ section.js

import Parse from 'parse'
import _ from 'lodash'

Parse.initialize('APP_ID', 'CLIENT_ID')

const Section = {}

...

Section.save = (json) => {
  const section = new ParseSection()
  return section.save(json)
}

我该怎么做呢,所以我只需要编写一次savefind方法,然后使用它们,例如Document.saveSection.save

1 个答案:

答案 0 :(得分:1)

一种方法是为每个实体(Parse.Object的子类)创建一个facade对象:

商品/ document.js

'use strict'

const ParseFacade = require('./parse-facade')

const Document = new ParseFacade('Document')

module.exports = Document

商品/ section.js

'use strict'

const ParseFacade = require('./parse-facade')

const Section = new ParseFacade('Section')

module.exports = Section

<强>解析-facade.js

'use strict'

const Parse = require('parse')
const _ = require('lodash')

Parse.initialize('APP_ID', 'CLIENT_ID')

function ParseFacade (className) {
    this.ParseObject = Parse.Object.extend(className)
}

ParseFacade.prototype.save = function save (json) {
    const PO = this.ParseObject
    const document = new PO()
    return document.save(json)
}

ParseFacade.prototype.find = function find () {
    const PO = this.ParseObject
    const query = new Parse.Query(PO)
    return query.find().then((results) =>
        _.map(results, (result) => result.toJSON()))
}

module.exports = ParseFacade

要向给定实体添加功能,请照常添加属性:

Document.doSomething = function doSomething (...args) {
    // this.ParseObject refers to the subclassed Parse.Object
    // ...
}