Ir al contenido
Menú
Se marcó esta pregunta
4 Respuestas
3615 Vistas

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

Avatar
Descartar
Autor

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

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

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

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

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)

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. 

Avatar
Descartar
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);
    }   
}

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

Publicaciones relacionadas Respuestas Vistas Actividad
4
may 25
1350
2
may 25
4699
1
mar 25
831
4
mar 25
3541
3
feb 25
4282