JS Service

v0.9.5+

JS service 和 Weex 实例在 JS runtime 中并行运行。Weex 实例的生命周期可调用 JS service 生命周期。目前提供创建、刷新、销毁生命周期。

重要提醒: JS Service 非常强大但也很危险,请小心使用!

注册 JS Service

iOS

  1. [WeexSDKEngine registerService:@"SERVICE_NAME" withScript: @"SERVICE_JS_CODE" withOptions: @{}];

Android

  1. HashMap<String, String> options = new HashMap<>()
  2. options.put("k1", "v1")
  3. String SERVICE_NAME = "SERVICE_NAME"
  4. String SERVICE_JS_CODE = "SERVICE_JS_CODE"
  5. boolean result = WXSDKEngine.registerService(SERVICE_NAME, SERVICE_JS_CODE, options)

Web

  1. <!-- 必须在 JSFM 之后加载 -->
  2. <script src="SERVICE_JS_CODE_URL"></script>

编写一个 JS service

  1. // options: native inject options
  2. // options.serviceName is native options name
  3. service.register(options.serviceName, {
  4. /**
  5. * JS Service lifecycle. JS Service `create` will before then each instance lifecycle `create`. The return param `instance` is Weex protected param. This object will return to instance global. Other params will in the `services` at instance.
  6. *
  7. * @param {String} id instance id
  8. * @param {Object} env device environment
  9. * @return {Object}
  10. */
  11. create: function(id, env, config) {
  12. return {
  13. instance: {
  14. InstanceService: function(weex) {
  15. var modal = weex.requireModule('modal')
  16. return {
  17. toast: function(title) {
  18. modal.toast({ message: title })
  19. }
  20. }
  21. }
  22. },
  23. NormalService: function(weex) {
  24. var modal = weex.requireModule('modal')
  25. return {
  26. toast: function(title) {
  27. modal.toast({ message: title })
  28. }
  29. }
  30. }
  31. }
  32. },
  33. /**
  34. * JS Service lifecycle. JS Service `refresh` will before then each instance lifecycle `refresh`. If you want to reset variable or something on instance refresh.
  35. *
  36. * @param {String} id instance id
  37. * @param {Object} env device environment
  38. */
  39. refresh: function(id, env, config){
  40. },
  41. /**
  42. * JS Service lifecycle. JS Service `destroy` will before then each instance lifecycle `destroy`. You can deleted variable here. If you doesn't detete variable define in JS Service. The variable will always in the js runtime. It's would be memory leak risk.
  43. *
  44. * @param {String} id instance id
  45. * @param {Object} env device environment
  46. * @return {Object}
  47. */
  48. destroy: function(id, env) {
  49. }
  50. })

Using JS Service (vuejs)

  1. <script>
  2. var _InstanceService = new InstanceService(weex)
  3. var _NormalService = new service.normalService(weex)
  4. module.exports = {
  5. created: fucntion() {
  6. // called modal module to toast something
  7. _InstanceService.toast('Instance JS Service')
  8. _NormalService.toast('Normal JS Service')
  9. }
  10. }
  11. </script>