Ir al contenido
Odoo Menú
  • Identificarse
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • TPV para tiendas
    • TPV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en directo
    • e-learning
    Cadena de suministro
    • Inventario
    • Fabricación
    • PLM
    • Compra
    • Mantenimiento
    • Calidad
    Recursos Humanos
    • Empleados
    • Reclutamiento
    • Ausencias
    • Evaluación
    • Referencias
    • Flota
    Marketing
    • Marketing social
    • Marketing por correo electrónico
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyecto
    • Partes de horas
    • Servicio de campo
    • Servicio de asistencia
    • Planificación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Conocimientos
    • WhatsApp
    Aplicaciones de terceros Studio de Odoo Plataforma de Odoo Cloud
  • Industrias
    Comercio al por menor
    • Librería
    • Tienda de ropa
    • Tienda de muebles
    • Tienda de ultramarinos
    • Ferretería
    • Juguetería
    Alimentación y hostelería
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidor de bebidas
    • Hotel
    Inmueble
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión inmobiliaria
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Empresa contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Fabricación
    • Textil
    • Metal
    • Muebles
    • Alimentos
    • Cervecería
    • Regalos de empresas
    Salud y bienestar
    • Club deportivo
    • Óptica
    • Gimnasio
    • Terapeutas
    • Farmacia
    • Peluquería
    Oficios
    • Handyman
    • Hardware y soporte técnico
    • Sistemas de energía solar
    • Zapatero
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin ánimo de lucro
    • Agencia de protección del medio ambiente
    • Alquiler de paneles publicitarios
    • Estudio fotográfico
    • Alquiler de bicicletas
    • Distribuidor de software
    Explorar todos los sectores
  • Comunidad
    Aprender
    • Tutoriales
    • Documentación
    • Certificaciones
    • Formación
    • Blog
    • Podcast
    Potenciar la educación
    • Programa de formación
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtener el software
    • Descargar
    • Comparar ediciones
    • Versiones
    Colaborar
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Convertirse en partner
    • Servicios para partners
    • Registrar tu empresa contable
    Obtener servicios
    • Encontrar un partner
    • Encontrar un asesor fiscal
    • Contacta con un experto
    • Servicios de implementación
    • Referencias de clientes
    • Ayuda
    • Actualizaciones
    GitHub YouTube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicitar una demostración
  • Precios
  • Ayuda

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

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyecto
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

Using useBus hook in Odoo 17

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
v17useBus
4 Respuestas
6892 Vistas
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
Descartar
David Norton
Autor

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

Avatar
David Norton
Autor Mejor respuesta

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
Descartar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Mejor respuesta

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
Descartar
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
Mejor respuesta

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
Descartar
Avatar
Shajahan
Mejor respuesta

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

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Inscribirse
Publicaciones relacionadas Respuestas Vistas Actividad
Ya es posible hacer Upgrade de v17 a v17.1 ?
v17
Avatar
Avatar
1
oct 25
1432
How to add a new Many2one field in res.config.settings? Resuelto
v17
Avatar
Avatar
Avatar
Avatar
4
oct 25
4040
Add field to ALL models in Odoo
v17
Avatar
Avatar
Avatar
2
sept 25
2623
How to disable Email notification - You have been assigned to Resuelto
v17
Avatar
Avatar
Avatar
Avatar
4
sept 25
8147
Selection Field Options Disappear from Database (PostgreSQL enum) on Module Upgrade
v17
Avatar
0
ago 25
1426
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento Odoo.sh
  • Ayuda
  • Actualizar
  • Desarrollos personalizados
  • Educación
  • Encontrar un asesor fiscal
  • Encontrar un partner
  • Convertirse en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contacta con nosotros
  • Puestos de trabajo
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Información legal • Privacidad
  • Seguridad
الْعَرَبيّة 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 es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y totalmente integrado.

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