rewarded-video-ad.js 2.2 KB
Newer Older
d-u-a's avatar
d-u-a 已提交
1 2 3 4 5 6 7

const eventNames = [
  'load',
  'close',
  'error'
]

d-u-a's avatar
d-u-a 已提交
8 9
const ERROR_CODE_LIST = [-5001, -5002, -5003, -5004, -5005, -5006]

d-u-a's avatar
d-u-a 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
class RewardedVideoAd {
  constructor (adpid) {
    this._options = {
      adpid: adpid
    }

    const _callbacks = this._callbacks = {}
    eventNames.forEach(item => {
      _callbacks[item] = []
      const name = item[0].toUpperCase() + item.substr(1)
      this[`on${name}`] = function (callback) {
        _callbacks[item].push(callback)
      }
    })

    this._isLoad = false
d-u-a's avatar
d-u-a 已提交
26
    this._adError = ''
d-u-a's avatar
d-u-a 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
    this._loadPromiseResolve = null
    this._loadPromiseReject = null
    const rewardAd = this._rewardAd = plus.ad.createRewardedVideoAd(this._options)
    rewardAd.onLoad((e) => {
      this._isLoad = true
      this._dispatchEvent('load', {})
      if (this._loadPromiseResolve != null) {
        this._loadPromiseResolve()
        this._loadPromiseResolve = null
      }
    })
    rewardAd.onClose((e) => {
      this._loadAd()
      this._dispatchEvent('close', { isEnded: e.isEnded })
    })
    rewardAd.onError((e) => {
43 44
      const { code, message } = e
      const data = { code: code, errMsg: message }
d-u-a's avatar
d-u-a 已提交
45
      this._adError = message
46
      this._dispatchEvent('error', data)
d-u-a's avatar
d-u-a 已提交
47
      if ((code === -5005 || ERROR_CODE_LIST.index(code) === -1) && this._loadPromiseReject != null) {
48
        this._loadPromiseReject(data)
d-u-a's avatar
d-u-a 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
        this._loadPromiseReject = null
      }
    })
    this._loadAd()
  }
  load () {
    return new Promise((resolve, reject) => {
      if (this._isLoad) {
        resolve()
        return
      }
      this._loadPromiseResolve = resolve
      this._loadPromiseReject = reject
      this._loadAd()
    })
  }
  show () {
    return new Promise((resolve, reject) => {
      if (this._isLoad) {
        this._rewardAd.show()
        resolve()
      } else {
d-u-a's avatar
d-u-a 已提交
71
        reject(new Error(this._adError))
d-u-a's avatar
d-u-a 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
      }
    })
  }
  _loadAd () {
    this._isLoad = false
    this._rewardAd.load()
  }
  _dispatchEvent (name, data) {
    this._callbacks[name].forEach(callback => {
      if (typeof callback === 'function') {
        callback(data || {})
      }
    })
  }
}

export function createRewardedVideoAd ({
  adpid = ''
} = {}) {
  return new RewardedVideoAd(adpid)
}