跳至内容
Odoo 菜单
  • 登录
  • 免费试用
  • 应用程序
    财务
    • 会计
    • 发票
    • 费用
    • 电子表格 (BI)
    • 文档
    • 电子签名
    销售
    • 客户关系管理
    • 销售
    • POS 销售点管理-零售
    • POS 销售点管理 - 餐厅
    • 订阅
    • 租赁
    网站
    • 网站设计
    • 电子商务
    • 博客
    • 论坛
    • 在线客服
    • 在线学习
    供应链
    • 库存
    • 制造
    • 产品生命周期
    • 采购
    • 维护保养
    • 品控
    人力资源
    • 员工
    • 招聘
    • 休假
    • 评价
    • 内部推荐
    • 车队
    营销
    • 社媒营销
    • 电邮营销
    • 短信营销
    • 近期活动
    • 营销自动化
    • 网上调查
    服务
    • 项目管理
    • 工时单
    • 现场服务
    • 服务台
    • 排期
    • 预约
    生产力
    • 讨论
    • 批核
    • IoT物联网
    • VoIP
    • 知识库
    • WhatsApp
    第三方应用软件 Odoo 定制 Odoo云端平台
  • 行业
    零售
    • 书店
    • 服装店
    • 家具店
    • 食品杂货店
    • 五金店
    • 玩具店
    餐饮与酒店服务
    • 酒吧及酒馆
    • 餐厅
    • 快餐
    • 民宿
    • 饮品分销商
    • 酒店
    房地产
    • 房地产代理
    • 建筑师事务所
    • 建造业
    • 地产管理
    • 园艺
    • 业主协会
    咨询
    • 会计师事务所
    • Odoo合作伙伴
    • 市场推广公司
    • 律师事务所
    • 人才招聘
    • 审核 & 认证
    制造
    • 纺织
    • 金属
    • 家具
    • 食品
    • 啤酒厂
    • 企业礼品
    保健与健身
    • 体育俱乐部
    • 眼镜店
    • 健身中心
    • 健康从业者
    • 药房
    • 发型屋
    商贸服务
    • 维修人员
    • IT 硬件及支持
    • 太阳能系统
    • 鞋匠
    • 清洁服务
    • 暖通空调服务
    其他
    • 非营利组织
    • 环境机构
    • 广告牌租赁
    • 摄影服务
    • 自行车租赁
    • 软件经销商
    浏览所有行业
  • 社区
    学习
    • 教学视频
    • 文档
    • 认证
    • 培训
    • 博客
    • 播客
    赋能教育
    • 教育计划
    • Scale Up! 商业游戏
    • 参观Odoo
    获取软件
    • 下载
    • 版本对比
    • 发布
    合作
    • Github
    • 论坛
    • 近期活动
    • 翻译
    • 成为合作伙伴
    • 合作伙伴服务
    • 注册您的会计事务所
    获取服务
    • 寻找合作伙伴
    • 查找会计服务
    • 预约顾问咨询
    • 安装及推行服务
    • 客户参考
    • 支持
    • 升级
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    获取演示
  • 定价
  • 技术支持

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • 客户关系管理
  • e-Commerce
  • 会计
  • 库存
  • PoS
  • 项目
  • MRP
All apps
只限注册用戶才可与社群互动。
所有帖文 人 徽章
标签 (查看所有)
odoo accounting v14 pos v15
关于此论坛区
只限注册用戶才可与社群互动。
所有帖文 人 徽章
标签 (查看所有)
odoo accounting v14 pos v15
关于此论坛区
帮助

Using useBus hook in Odoo 17

订阅

此帖文有活动时,接收通知

此问题已终结
v17useBus
4 回复
6896 查看
形象
David Norton

Hi community

I am trying to find out how the useBus hook works. It has changed from previous versions and there seems to be no examples anywhere that are up to date. Using the awesome_owl framework I have the modified the world-renowned counter component as follows:

/** @odoo-module */

// counter.js
import { Component, useState } from "@odoo/owl";
import { useBus } from "@web/core/utils/hooks";

export class Counter extends Component {
    static template = "awesome_owl.Counter";

    setup() {
        this.state = useState({ value: 1 });
        useBus(this.env.bus, "some-event", event => {
            console.log(event);
          });
    }

    increment() {
        //this.state.value = this.state.value + 1;
        this.callApi(this.state.value);
    }

    callApi(val) {
        window.location.replace("/test?state=" + val);
    }   
} 



   
       

            Counter:
           
                            style="font-family:'console' width: 100%; height: 600px;  overflow-y: auto;color:rgb(255,255,255);  background: black;"
                readonly="1">

       

   

and in the controllers.py, I have added a new route

    @http.route(['/test'], type='http', auth='public')
    def call_incrementor(self, **args):
        _logger.info('**************************************************************************************')
        _logger.info('Controller called. state=' + args["state"] )

        count = args["state"] + 1
        channel = "counter_channel"
        rtn_data = {'new_state': count}
        message = {
            "data": rtn_data,
            "channel": channel
        }
        request.env["bus.bus"]._sendone(channel, "notification", message)
        return {'result': 'Live data sent successfully'}
//return request.render('awesome_owl.playground') #added temporarily to complete the loop

The starts are added so I can find the output in the log easily.

So I have 2 problems (questions)

  1. Since you can no longer add a channel to the bus service/hook, how to get the results to the frontend, and
  2. I get an error immediately when using the useBus Hook as follows
Error: The following error occurred in onMounted: "Cannot read properties of undefined (reading 'addEventListener')"
    at wrapError (http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:10189:23)
    at onMounted (http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:10242:27)
    at useEffect (http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:13484:9)
    at useBus (http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:39138:5)
    at Counter.setup (http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:42321:9)
    at new ComponentNode (http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:9941:28)
    at http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:13345:28
    at Playground.template (eval at compile (http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:13116:20), :12:16)
    at MountFiber._render (http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:9306:38)
    at MountFiber.render (http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:9298:18)
Caused by: TypeError: Cannot read properties of undefined (reading 'addEventListener')
    at http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:39141:17
    at Counter. (http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:13486:23)
    at http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:10204:32
    at MountFiber.complete (http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:9420:29)
    at Scheduler.processFiber (http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:13199:27)
    at Scheduler.processTasks (http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:13175:22)
    at http://192.168.0.10:8069/web/assets/debug/awesome_owl.assets_playground.js:13165:68
logError @ main.js:37


Your help would be much appreciated

0
形象
丢弃
David Norton
编写者

Ok my xml didn't display well at all but it is unchanged from the original

形象
David Norton
编写者 最佳答案

Despite my comment, Shajahan's answer didn't work but it helped me find and resolve the issues. I never managed to get the useBus hook working, but I did resolve my initial problem. It was that rather than using mount to mount the Playground component (in main.js), I use "mountComponent" from "@web/env". It seems that it sets up more plumbing in the background and sets up this.env.bus amongst other things. We learn every day.

What I wanted was to send the current counter value to the python controller, have it increment the value and send it back to the front end. I gave up on the bus and achieved it with a simple reply. Because of the lack of complete examples out there, I decided to re-post here. Maybe it will help somebody.  In the interests of education, I left all my debug statements in the code.

counter.xml was unchanged so I won't try to post again. It was bad enough last time.

controllers.py

from odoo import http
from odoo.http import request, route

import logging
_logger = logging.getLogger(__name__)
import json

class OwlPlayground(http.Controller):
    @http.route(['/awesome_owl'], type='http', auth='public')
    def show_playground(self):
        return request.render('awesome_owl.playground')

class Incrementor(http.Controller):
    @http.route(['/test'], type='http', auth='public')
    def handler(self, **args):
        if "state" in args:
            new_count = int(args["state"]) + 1
            rtn_data = {'new_state': new_count}
        else:   
            rtn_data = {'new_state': 0}
        response = json.dumps(rtn_data)   
        return response

counter.js - I added the WebClient class to stick with what I know. Please note, the call is synchronous so will block your page if there is an error. This is just to get things happening in the right order. 

/** @odoo-module */
import { Component, useState } from "@odoo/owl";

var WebClient = function() {
    this.get = function(url, callback) {
        var request = new XMLHttpRequest();
        request.onreadystatechange = function() {
            if (request.readyState == 4 && request.status == 200)
                console.log("Replied ...")
                callback(request.responseText);
        }
        request.open( "GET", url, false ); 
        console.log("Sent....");
        request.send( null );
    }
}

export class Counter extends Component {
    static template = "awesome_owl.Counter";
    static props = {};

    setup() {
        this.state = useState({ value: 1 });
        console.log("setup");
    }

    set_state(val) {
        console.log("val=" + val);
        this.state.value = val;
    }

    increment(obj) {
        let val=this.state.value
        console.log("callApi");
        var client = new WebClient(true);
        var client_response = "";
        client.get('/test?state='+val, function(response) {
            if(response) {
                console.log("Response=" + response);
                client_response = response;
                console.log("client_response=" + client_response);
            }
        });
        console.log("client_response=" + client_response);
        if(client_response) {
            const responseJson = JSON.parse(client_response);
            console.log("responseJson type=" + typeof responseJson )
            if(responseJson && responseJson.new_state > 0) {
                console.log("new_state=" + responseJson.new_state);
                console.log("type=" + typeof responseJson.new_state )
                this.set_state(responseJson.new_state);
            }
        }
    }
}

It's not elegant but it works

0
形象
丢弃
形象
Cybrosys Techno Solutions Pvt.Ltd
最佳答案

Hi,

You can define the usebus in the setup of your JS file as like useBus(this.env.bus, "some-event", (event) => {

            console.log(event);

          });


And if you need to trigger or call this bus from any other js file , you can just trigger it by

this.env.bus.trigger('some-event',{})

You can call the above in side the function in which you need to trigger the bus


Hope it helps

1
形象
丢弃
David Norton
编写者

Thank you for your comment. My main issue is triggering the event from a python controller (Server-side events). I can't believe this is so difficult when all the functions appear to be there - and I know it happens in the discuss module, so it is possible, but just not using the useBus hook. I would love to see a full example if someone out there has it.

David Norton
编写者

In the past you could add a channel to the bus to direct server-side events to the client. It appears that this functionality has been removed (unless I have missed something, but I have been at it for 2 weeks)

形象
Ramya Loganathan
最佳答案

I am stuck at this problem, I want to push a bus notification to user from controller. I tried all the method posted but it is not working in Odoo 17. Does anyone have the bus service working from controller. 

0
形象
丢弃
形象
Shajahan
最佳答案

- Ensure that this.env.bus is defined and correctly refers to a valid bus object with an addEventListener method. It's possible that this.env.bus is not properly initialized when useBus is called.
- Check if the hook is being used at the right lifecycle stage of the component. Since useBus is likely setting up event listeners, it should be used within a setup function or similar initialization function where this.env.bus is guaranteed to be available.

Here's a slight modification to check for the availability of this.env.bus and better handle the lifecycle:

import { Component, useState, onMounted, onWillUnmount } from "@odoo/owl";

export class Counter extends Component {
    static template = "awesome_owl.Counter";

    setup() {
        this.state = useState({ value: 1 });

        onMounted(() => {
            if (this.env.bus && typeof this.env.bus.addEventListener === 'function') {
                this.env.bus.addEventListener('some-event', this.handleEvent);
            }
        });

        onWillUnmount(() => {
            if (this.env.bus && typeof this.env.bus.removeEventListener === 'function') {
                this.env.bus.removeEventListener('some-event', this.handleEvent);
            }
        });
    }

    handleEvent(event) {
        console.log(event);
    }

    increment() {
        this.callApi(this.state.value);
    }

    callApi(val) {
        window.location.replace("/test?state=" + val);
    }   
}

-1
形象
丢弃
David Norton
编写者

@Shahjahan - thank you for your answer which works 100%. I had assumed that the useBus hook would set up everything correctly but simply cannot get anything out of it.

喜欢讨论吗?不要只阅读,加入进来!

立即创建账户,享受专属功能,与我们的精彩社区互动!

注册
相关帖文 回复 查看 活动
Ya es posible hacer Upgrade de v17 a v17.1 ?
v17
形象
形象
1
10月 25
1434
How to add a new Many2one field in res.config.settings? 已解决
v17
形象
形象
形象
形象
4
10月 25
4045
Add field to ALL models in Odoo
v17
形象
形象
形象
2
9月 25
2627
How to disable Email notification - You have been assigned to 已解决
v17
形象
形象
形象
形象
4
9月 25
8149
Selection Field Options Disappear from Database (PostgreSQL enum) on Module Upgrade
v17
形象
0
8月 25
1427
社区
  • 教学视频
  • 文档
  • 论坛
开源
  • 下载
  • Github
  • Runbot
  • 翻译
服务
  • Odoo.sh 托管
  • 支持
  • 升级
  • 自定义开发服务
  • 教育
  • 查找会计服务
  • 寻找合作伙伴
  • 成为合作伙伴
关于我们
  • 我们的公司
  • 品牌资产
  • 联系我们
  • 招聘
  • 近期活动
  • 播客
  • 博客
  • 客户
  • 法律 • 隐私
  • 安全
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo致力于为企业管理提供高效智能的开源解决方案,是全球业内高速成长的软件服务商之一,逾七百五十万用户选择Odoo进行数字化升级。通过一系列全业务链覆盖、高度集成、简单易用的商业应用,助力企业实现信息化改革、降本增效并释放公司增长潜力。

Odoo独特的价值在于是一款非常容易使用又完全集成的应用。

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now