Přejít na obsah
Odoo Menu
  • Přihlásit se
  • Vyzkoušejte zdarma
  • Aplikace
    Finance
    • Účetnictví
    • Fakturace
    • Výdaje
    • Spreadsheet (BI)
    • Dokumenty
    • Podpisy
    Prodej
    • CRM
    • Prodej
    • POS Obchod
    • POS Restaurace
    • Předplatné
    • Pronájem
    Webové stránky
    • Webové stránky
    • E-shop
    • Blog
    • Fórum
    • Živý chat
    • eLearning
    Dodavatelský řetězec
    • Sklad
    • Výroba
    • PLM
    • Nákup
    • Údržba
    • Kvalita
    Lidské zdroje
    • Zaměstnanci
    • Nábor
    • Volno
    • Hodnocení zaměstnanců
    • Doporučení
    • Vozový park
    Marketing
    • Marketing sociálních sítí
    • Emailový marketing
    • SMS Marketing
    • Události
    • Marketingová automatizace
    • Dotazníky
    Služby
    • Projekt
    • Časové výkazy
    • Práce v terénu
    • Helpdesk
    • Plánování
    • Schůzky
    Produktivita
    • Diskuze
    • Schvalování
    • IoT
    • VoIP
    • Znalosti
    • WhatsApp
    Aplikace třetích stran Odoo Studio Odoo cloudová platforma
  • Branže
    Maloobchod
    • Knihkupectví
    • Obchod s oblečením
    • Obchod s nábytkem
    • Potraviny
    • Obchod s hardwarem
    • Hračkářství
    Jídlo a pohostinství
    • Bar a Pub
    • Restaurace
    • Fast Food
    • Penzion
    • Distributor nápojů
    • Hotel
    Nemovitost
    • Realitní kancelář
    • Architektonická firma
    • Stavba
    • Správa nemovitostí
    • Zahradnictví
    • Asociace vlastníků nemovitosti
    Poradenství
    • Účetní firma
    • Odoo Partner
    • Marketingová agentura
    • Právník
    • Akvizice talentů
    • Audit a certifikace
    Výroba
    • Textil
    • Kov
    • Nábytek
    • Jídlo
    • Pivovar
    • Korporátní dárky
    Zdraví a fitness
    • Sportovní klub
    • Prodejna brýli
    • Fitness Centrum
    • Wellness praktikové
    • Lékárna
    • Kadeřnictví
    Transakce
    • Údržbář
    • Podpora IT & hardware
    • Systémy solární energie
    • Výrobce obuvi
    • Úklidové služby
    • Služby HVAC
    Ostatní
    • Nezisková organizace
    • Agentura pro životní prostředí
    • Pronájem billboardů
    • Fotografování
    • Leasing jízdních kol
    • Prodejce softwaru
    Procházet všechna odvětví
  • Komunita
    Edukační program
    • Tutoriály
    • Dokumentace
    • Certifikace
    • Vzdělávání
    • Blog
    • Podcast
    Podpora vzdělávání
    • Vzdělávací program
    • Scale Up! Hra na firmu
    • Navštivte Odoo
    Získat software
    • Stáhnout
    • Porovnejte edice
    • Verze
    Spolupráce
    • Github
    • Fórum
    • Události
    • Překlady
    • Stát se partnerem
    • Služby pro partnery
    • Registrujte svou účetní firmu
    Získat služby
    • Najít partnera
    • Najít účetní
    • Setkejte se s poradcem
    • Implementační služby
    • Zákaznické reference
    • Podpora
    • Upgrady
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Dohodnout demo
  • Ceník
  • Pomoc

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

  • CRM
  • e-Commerce
  • Účetnictví
  • Sklad
  • PoS
  • Projekty
  • MRP
All apps
You need to be registered to interact with the community.
All Posts Lidé Odznaky
Štítky (View all)
odoo accounting v14 pos v15
O tomto fóru
You need to be registered to interact with the community.
All Posts Lidé Odznaky
Štítky (View all)
odoo accounting v14 pos v15
O tomto fóru
Pomoc

Using useBus hook in Odoo 17

Odebírat

Get notified when there's activity on this post

This question has been flagged
v17useBus
4 Odpovědi
6911 Zobrazení
Avatar
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
Avatar
Zrušit
David Norton
Autor

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

Avatar
David Norton
Autor Nejlepší odpověď

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
Avatar
Zrušit
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Nejlepší odpověď

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
Avatar
Zrušit
David Norton
Autor

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
Autor

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)

Avatar
Ramya Loganathan
Nejlepší odpověď

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
Avatar
Zrušit
Avatar
Shajahan
Nejlepší odpověď

- 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
Avatar
Zrušit
David Norton
Autor

@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.

Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Přihlásit se
Related Posts Odpovědi Zobrazení Aktivita
Ya es posible hacer Upgrade de v17 a v17.1 ?
v17
Avatar
Avatar
1
říj 25
1435
How to add a new Many2one field in res.config.settings? Vyřešeno
v17
Avatar
Avatar
Avatar
Avatar
4
říj 25
4052
Add field to ALL models in Odoo
v17
Avatar
Avatar
Avatar
2
zář 25
2631
How to disable Email notification - You have been assigned to Vyřešeno
v17
Avatar
Avatar
Avatar
Avatar
4
zář 25
8157
Selection Field Options Disappear from Database (PostgreSQL enum) on Module Upgrade
v17
Avatar
0
srp 25
1431
Komunita
  • Tutoriály
  • Dokumentace
  • Fórum
Open Source
  • Stáhnout
  • Github
  • Runbot
  • Překlady
Služby
  • Odoo.sh hostování
  • Podpora
  • Upgrade
  • Nestandardní vývoj
  • Edukační program
  • Najít účetní
  • Najít partnera
  • Stát se partnerem
O nás
  • Naše společnost
  • Podklady značky
  • Kontakujte nás
  • Práce
  • Události
  • Podcast
  • Blog
  • Zákazníci
  • Právní dokumenty • Soukromí
  • Zabezpečení
الْعَرَبيّة 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 je balíček open-source aplikací, které pokrývají všechny potřeby vaší společnosti: CRM, e-shop, účetnictví, sklady, kasy, projektové řízení a další.

Unikátní nabídka od Odoo poskytuje velmi jednoduché uživatelské rozhraní a vše je integrované na jednom místě.

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