微信小程序实战中位置闹铃如何实现监控点状态迁移功能

微信小程序实战中位置闹铃如何实现监控点状态迁移功能

这篇文章给大家介绍微信小程序实战中位置闹铃如何实现监控点状态迁移功能,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

接近监控点

enterAlarmCheck: function (distance, accuracy){

   if (this.state == 'ready') {

     //500m

     if (distance < 500) {

       this.checkBuffer.push(1)

     } else {

       this.checkBuffer.push(-1)

     }

     if (this.checkBuffer.length > CHECK_BUFFER_SIZE){

       this.checkBuffer.shift()

     }

     var sum = this.checkBuffer.reduce(function(x,y){return x + y}, 0)

     if (sum == CHECK_BUFFER_SIZE) {

       this.setState('armed')

     }

   } else if (this.state == 'armed') {

     //100m

     if (distance < 100) {

       this.checkBuffer.push(1)

     } else if (distance > 500) {

       this.checkBuffer.push(-1)

     }

     if (this.checkBuffer.length > CHECK_BUFFER_SIZE) {

       this.checkBuffer.shift()

     }

     var sum = this.checkBuffer.reduce(function (x, y) { return x + y }, 0)

     if (sum == CHECK_BUFFER_SIZE) {

       this.setState('fired')

     }else if (sum == -CHECK_BUFFER_SIZE) {

       this.setState('ready')

     }

   } else if (this.state == 'fired'){ //fired

     this.checkBuffer.push(1)

     if(this.checkBuffer.length == 10){

       this.setState('accepted')

     }

   } else{

     if (distance > 100) {

       this.checkBuffer.push(1)

     } else {

       this.checkBuffer.push(-1)

     }

     if (this.checkBuffer.length > CHECK_BUFFER_SIZE) {

       this.checkBuffer.shift()

     }

     var sum = this.checkBuffer.reduce(function (x, y) { return x + y }, 0)

     if (sum == CHECK_BUFFER_SIZE) {

       this.setState('ready')

     }

   }

 },

补充说明

代码中最难理解的恐怕不是状态迁移本身,而是数组的用法。这里简单地说明一下。

push:在数据最后添加元素

shift:从数组开头删除元素

reduce:函数本身可以提供上次操作的结果并逐一对每个元素进行操作,这里用作数组所有元素地求和。

再回头看一遍,相信程序很容易理解。

最新状态图

在实现状态迁移地过程中,对状态图也进行了适当地修改,以下是最新的状态图。

微信小程序实战中位置闹铃如何实现监控点状态迁移功能

关于微信小程序实战中位置闹铃如何实现监控点状态迁移功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。