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. /**
35. * JS Service lifecycle. JS Service `refresh` will before then each instance lifecycle `refresh`. If you want to reset variable or something on instance refresh.
36. *
37. * @param {String} id instance id
38. * @param {Object} env device environment
39. */
40. refresh: function(id, env, config){
41. 42. },
43. 44. /**
45. * 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.
46. *
47. * @param {String} id instance id
48. * @param {Object} env device environment
49. * @return {Object}
50. */
51. destroy: function(id, env) {
52. 53. }
54. })
Using JS Service (vuejs)
1. <script>
2. var _InstanceService = new InstanceService(weex)
3. var _NormalService = new service.normalService(weex)
4. 5. module.exports = {
6. created: fucntion() {
7. // called modal module to toast something
8. _InstanceService.toast('Instance JS Service')
9. _NormalService.toast('Normal JS Service')
10. }
11. }
12. </script>
