JS Service
优质
小牛编辑
135浏览
2023-12-01
JSService 和 Weex 实例在 JS Runtime 中并行运行。Weex 实例的生命周期可调用 JSService 生命周期。目前提供创建、刷新、销毁生命周期。
重要提醒: JSService 使用不当会导致内存增高或全局污染!
JS 内置文件示例
service.register(SERVICE_NAME /* same string with native */, {
/**
* JSService lifecycle. JSService `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.
*
* @param {String} id instance id
* @param {Object} env device environment
* @return {Object}
*/
create: function(id, env, config) {
return {
instance: {
InstanceService: function(weex) {
var modal = weex.requireModule('modal')
return {
toast: function(title) {
modal.toast({ message: title })
}
}
}
},
NormalService: function(weex) {
var modal = weex.requireModule('modal')
return {
toast: function(title) {
modal.toast({ message: title })
}
}
}
}
},
/**
* JSService lifecycle. JSService `refresh` will before then each instance lifecycle `refresh`. If you want to reset variable or something on instance refresh.
*
* @param {String} id instance id
* @param {Object} env device environment
*/
refresh: function(id, env, config){
},
/**
* JSService lifecycle. JSService `destroy` will before then each instance lifecycle `destroy`. You can deleted variable here. If you doesn't detete variable define in JSService. The variable will always in the js runtime. It's would be memory leak risk.
*
* @param {String} id instance id
* @param {Object} env device environment
* @return {Object}
*/
destroy: function(id, env) {
}
})
调用 JSService
Rax 中全局读取 JSService
let service = __weex_config__.services.service;
// 当端内已经集成内置文件 SERVICE_NAME
console.error(typeof service[SERVICE_NAME]);
扩展阅读:Weex JSService