Skip to content

Instantly share code, notes, and snippets.

@pespantelis
Last active June 30, 2019 15:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pespantelis/cdf42a52e5bb8ee095a08abdb58c8edf to your computer and use it in GitHub Desktop.
Save pespantelis/cdf42a52e5bb8ee095a08abdb58c8edf to your computer and use it in GitHub Desktop.
Moment directive for Vue.js http://codepen.io/pespantelis/pen/oLLLMP
import Vue from 'vue'
import Moment from 'moment'
Vue.directive('moment-ago', {
update (timestamp) {
this.el.innerHTML = Moment(timestamp).fromNow()
this.interval = setInterval(() => {
this.el.innerHTML = Moment(timestamp).fromNow()
}, 1000)
},
unbind () {
clearInterval(this.interval)
}
})
@bluedarker
Copy link

bluedarker commented Jun 15, 2016

@pespantelis

I have update you solution, It's only one setInterval now

import Vue from 'vue'
import moment from 'moment'



Vue.directive('moment-ago', {
  update (time) {
    this.el.innerHTML = moment(time).fromNow()

    //only register once
    if(!this.$momentAgoKey){
      this.$momentAgoKey=''+keyGenerate++
      funs[this.$momentAgoKey]= () => {
        this.el.innerHTML = moment(time).fromNow()
      }
      runAutoUpdate()
    }

  },

  unbind () {
    stopAutoUpdate(this.$momentAgoKey)
  }
})

var intervalTimes= 0,keyGenerate=1,funs={}
function runAutoUpdate(){
  if(intervalTimes!=0)return //only run once
  console.info('moment run')
  intervalTimes=setInterval(function(){
    for(var key in funs){
      funs[key]();
    }
  },1000)
}

function stopAutoUpdate(key){
  if(!key)return
  delete funs[key]
  if(isEmptyObj(funs)){
    clearInterval(intervalTimes)
    intervalTimes=0
  }

}

function isEmptyObj(obj){
  for(var key in obj){
    return false;
  }
  return true;
}

@bluedarker
Copy link

But still have problem, if use vue-router and setting keep-alive mode, inactive component still keep update

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