zoukankan      html  css  js  c++  java
  • 小程序如何改变onLoad 的执行时机?

    也许在小程序所有生命周期里,我们用的最多的就是 onLoad,一大堆代码都要在初始化的时候执行。很多时候,初始化的代码是每个页面共用的,比如获取用户信息、获取定位等:

    Page({
      onLoad() {
        this.userData = getUserData()
        wx.getLocation({
          type: 'wgs84',
          success (res) {
            // 业务代码
            // ...
          }
        })
      }
      // ...
    })

    久而久之,每个页面的 js 里都是如上的重复代码。如果可以先执行完通用的初始化代码,再执行每个页面各自的 onLoad 多好,可惜小程序并没有提供类似的钩子函数,那就自己来吧。

    代理 onLoad

    按照前几篇的方法,可以代理原有的 onLoad 事件:

    var originPage = Page
    
    function MyPage(config) {
      this.lifetimeBackup = {
        onLoad: config.onLoad
      }
      config.onLoad = function(options) {
        // 自定义代码
        // 公共的初始化代码
        this.userData = getUserData()
         wx.getLocation({
          type: 'wgs84',
          success (res) {
            // 执行 onLoad
            this.lifetimeBackup.onLoad.call(this, options)
          }
        })
      }
      
      // ...
    
      originPage(config)
    }

    当然,实际开发过程中的初始化代码不可能这么少,可以用很多方式把它抽离出去,比如这样:

    // utils/initial.js
    function initial(callback) {
      this.userData = getUserData()
      wx.getLocation({
        type: 'wgs84',
        success (res) {
          callback()
        }
      })
    }
      
    // utils/wx.js
    var initial = require('./initial')
    var originPage = Page
    
    function MyPage(config) {
      this.lifetimeBackup = {
        onLoad: config.onLoad
      }
      config.onLoad = function(options) {
        initial(() => {
          this.lifetimeBackup.onLoad.call(this, options)
        })
      }
      // ...
      originPage(config)
    }

    也可以使用更多高级的方法抽离出去,比如 event bus 之类的,就不多赘述。

    看似很简单,但其实这样忽略了一个问题 —— 生命周期顺序被打乱了!如果初始化方法里有异步代码,那首先执行的可能就是 onShow ,而不是约定的 onLoad。

    资源搜索网站大全 http://www.szhdn.com

    恢复生命周期顺序

    为了保证生命周期函数能够按顺序执行,可以先临时清空生命周期函数,然后再依次执行,如下代码所示:

    // utils/wx.js
    const LIFETIME_EVENTS = ['onLoad', 'onShow', 'onReady']
    var initial = require('./initial')
    var originPage = Page
    
    
    function MyPage(config) {
      LIFETIME_EVENTS.forEach((event) => {
        // 备份生命周期函数
        this.lifetimeBackup[event] = config[event]
        // 临时清空
        config[event] = function() {}
      })
      config.onLoad = function(options) {
        initial(() => {
          // 依次执行生命周期函数
          LIFETIME_EVENTS.forEach((event) => {
            this.lifetimeBackup[event].call(this, options)
          })
        })
      }
      // ...
      originPage(config)
    }

    注意上述代码还是有问题的,当小程序业务跳走再返回或者切后台到前台时,onShow 无法正常触发,因为被设置为空函数了。

    为了保证 onShow 等生命周期函数的后续正常运行,需要在依次执行完生命周期函数后,再把它们恢复到 config 下,这是必不可少的。完整代码如下:

    // utils/wx.js
    const LIFETIME_EVENTS = ['onLoad', 'onShow', 'onReady']
    var initial = require('./initial')
    var originPage = Page
    
    
    function MyPage(config) {
      LIFETIME_EVENTS.forEach((event) => {
        // 备份生命周期函数
        this.lifetimeBackup[event] = config[event]
        // 临时清空
        config[event] = function() {}
      })
      config.onLoad = function(options) {
        initial(() => {
          // 依次执行生命周期函数
          LIFETIME_EVENTS.forEach((event) => {
            this.lifetimeBackup[event].call(this, options)
            // 执行完后,恢复过来
            config[event] = this.lifetimeBackup[event]
          })
        })
      }
      // ...
      originPage(config)
    }

    总结

    代理了 onLoad 后,就可以手动控制其执行的时机,可以折腾的事情就多了很多。比如当初始化函数需要执行(请求)的内容比较多,耗时比较长时,可以统一给页面增加一些 loading 提示等。总之,可以自由控制了。

  • 相关阅读:
    探索ASP.NET MVC5系列之~~~3.视图篇(下)---包含常用表单和暴力解猜防御
    探索ASP.NET MVC5系列之~~~2.视图篇(上)---包含XSS防御和异步分部视图的处理
    SVN:Previous operation has not finished; run 'cleanup' if it was interrupted
    探索ASP.NET MVC5系列之~~~1.基础篇---必须知道的小技能
    MVC:The name 'Scripts' does not exist in the current context
    Dapper.Contrib:GetAsync<T> only supports an entity with a [Key] or an [ExplicitKey] property
    Dapper扩展之~~~Dapper.Contrib
    AutoFac在项目中的应用
    群福利:百度云管家-本地SVIP
    【声明】前方不设坑位,不收费!~ 我为NET狂官方学习计划
  • 原文地址:https://www.cnblogs.com/xiaonian8/p/14025288.html
Copyright © 2011-2022 走看看