İçereği Atla
Odoo Menü
  • Portal
  • Ücretsiz deneyin
  • Uygulamalar
    Finans
    • Muhasebe
    • Faturalama
    • Masraf Yönetimi
    • Elektronik Çizelge (BI)
    • Belgeler
    • İmza
    Satış
    • Müşteri İlişkileri Yönetimi (CRM)
    • Satış
    • Satış Noktası Mağaza
    • Satış Noktası Restoran
    • Abonelikler
    • Kiralama
    Web Sitesi
    • Web Sitesi Oluşturucu
    • eTicaret
    • Blog
    • Forum
    • Canlı Sohbet
    • eÖğrenme
    Tedarik Zinciri
    • Envanter
    • Üretim
    • Ürün Yaşam Döngüsü Yönetimi
    • Satın Alma
    • Bakım
    • Kalite
    İnsan Kaynakları
    • Çalışanlar
    • İşe Alım
    • İzin
    • Değerlendirme
    • Referans
    • Filo Yönetimi
    Pazarlama
    • Sosyal Medyada Pazarlama
    • E-posta ile Pazarlama
    • SMS ile Pazarlama
    • Etkinlikler
    • Pazarlama Otomasyonu
    • Anket
    Hizmetler
    • Proje Yönetimi
    • Çalışma Çizelgeleri
    • Saha Hizmeti
    • Yardım Masası
    • Planlama
    • Randevular
    Verimlilik
    • Sohbet
    • Onay
    • Nesnelerin İnterneti
    • VoIP
    • Bilgi Bankası
    • WhatsApp
    Üçüncü taraf uygulamalar Odoo Stüdyo Odoo Bulut Platformu
  • Sektörler
    Perakende satış
    • Kitapçı
    • Giyim Mağazası
    • Mobilya Mağazası
    • Gıda Marketi
    • Hırdavat Dükkanı
    • Oyuncak Dükkanı
    Gıda ve Konaklama
    • Bar ve Pub
    • Restoran
    • Fast Food Restoranı
    • Konuk Evi
    • İçecek Distribütörü
    • Otel
    Gayrimenkul
    • Emlak Acentesi
    • Mimarlık Firması
    • İnşaat
    • Emlak Yönetimi
    • Bahçe Tasarımı
    • Mülk Sahipleri Derneği
    Uzmanlık
    • Muhasebe Firması
    • Odoo Partner
    • Pazarlama Ajansı
    • Hukuk Firması
    • Yetenek Kazanımı
    • Denetim ve Belgelendirme
    Üretim
    • Tekstil
    • Metal
    • Mobilyalar
    • Gıda
    • Bira fabrikası
    • Kurumsal Hediye
    Sağlık ve Spor
    • Spor Kulübü
    • Optik Mağazası
    • Fitness Merkezi
    • Sağlıklı Yaşam Merkezi
    • Eczane
    • Kuaför Salonu
    Ticaret
    • Tamirci
    • BT Donanım & Destek
    • Güneş Enerjisi Sistemleri
    • Ayakkabı İmalatçısı
    • Temizlik Hizmetleri
    • HVAC Hizmetleri
    Diğerleri
    • Kar Amacı Gütmeyen Kuruluş
    • Çevre Ajansı
    • Reklam Panosu Kiralama
    • Fotoğrafçılık
    • Bisiklet Kiralama
    • Yazılım Bayisi
    Tüm Sektörlere Göz Atın
  • Topluluk
    Öğrenim
    • Eğitim Araçları
    • Dokümantasyon
    • Sertifikasyonlar
    • Eğitim Etkinlikleri
    • Blog
    • Podcast
    Eğitim ve Gelişim
    • Eğitim Programı
    • Scale Up! İşletme Oyunu
    • Odoo'yu Ziyaret Edin
    Yazılım
    • İndirin
    • Sürümleri Kıyaslayın
    • Sürümler
    İş Birliği
    • Github
    • Forum
    • Etkinlikler
    • Çeviriler
    • Partner Olun
    • Partnerler için Hizmetler
    • Muhasebe Firmanızı Kaydettirin
    Hizmetler
    • Partner Bulun
    • Muhasebeci Bulun
    • Bir danışmanla görüşün
    • Kurulum Hizmetleri
    • Müşteri Referansları
    • Destek
    • Sürüm Yükseltme
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Demo randevusu alın
  • Fiyatlandırma
  • Yardım

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

  • Müşteri İlişkileri Yönetimi
  • e-Commerce
  • Muhasebe
  • Envanter
  • PoS
  • Proje Yönetimi
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiketler (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiketler (View all)
odoo accounting v14 pos v15
About this forum
Yardım

Using useBus hook in Odoo 17

Abone Ol

Get notified when there's activity on this post

Bu soru işaretlendi
v17useBus
4 Cevaplar
6917 Görünümler
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
Vazgeç
David Norton
Üretici

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

Avatar
David Norton
Üretici En İyi Yanıt

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
Vazgeç
Avatar
Cybrosys Techno Solutions Pvt.Ltd
En İyi Yanıt

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
Vazgeç
David Norton
Üretici

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
Üretici

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
En İyi Yanıt

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
Vazgeç
Avatar
Shajahan
En İyi Yanıt

- 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
Vazgeç
David Norton
Üretici

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

Üye Ol
İlgili Gönderiler Cevaplar Görünümler Aktivite
Ya es posible hacer Upgrade de v17 a v17.1 ?
v17
Avatar
Avatar
1
Eki 25
1436
How to add a new Many2one field in res.config.settings? Çözüldü
v17
Avatar
Avatar
Avatar
Avatar
4
Eki 25
4057
Add field to ALL models in Odoo
v17
Avatar
Avatar
Avatar
2
Eyl 25
2632
How to disable Email notification - You have been assigned to Çözüldü
v17
Avatar
Avatar
Avatar
Avatar
4
Eyl 25
8159
Selection Field Options Disappear from Database (PostgreSQL enum) on Module Upgrade
v17
Avatar
0
Ağu 25
1436
Topluluk
  • Eğitim Araçları
  • Dokümantasyon
  • Forum
Açık Kaynak
  • İndirin
  • Github
  • Runbot
  • Çeviriler
Hizmetler
  • Odoo.sh Hosting
  • Destek
  • Sürüm Yükseltme
  • Özel Geliştirmeler
  • Eğitim
  • Muhasebeci Bulun
  • Partner Bulun
  • Partner Olun
Hakkında
  • Şirketimiz
  • Pazarlama Gereçleri
  • İletişim
  • Kariyer
  • Etkinlikler
  • Podcast
  • Blog
  • Müşteriler
  • Hukuki • Gizlilik
  • Güvenlik
الْعَرَبيّة 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, müşteri ilişkileri yönetimi, eTicaret, muhasebe, envanter, satış noktası, proje yönetimi gibi şirketinizin tüm ihtiyaçlarını karşılayan bir açık kaynak işletme uygulamaları paketidir.

Odoo’nun eşsiz değer önermesi, aynı anda hem kullanımının çok kolay olup hem de tamamen entegre olmasıdır.

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