Odoo 10中点击按钮调用JavaScript函数无弹窗问题求助
Hey there! I’ve run into this exact issue before with Odoo 10’s JavaScript scoping rules—let’s break down why your clickMe() function isn’t firing and how to fix it.
The Root Cause
Odoo 10 uses RequireJS to manage JavaScript modules, which means any functions you define inside your .js file are locked within the module’s local scope by default. When you use onclick="clickMe()" on your button, the browser looks for clickMe() in the global window scope, where it doesn’t exist. That’s why your initial alert() worked (it ran immediately when the module loaded) but the function call fails.
Solution 1: Expose the Function to the Global Scope
The quickest fix is to explicitly attach your function to the window object so it’s accessible globally. Update your test.js file like this:
odoo.define('myModule.test', function(require) { "use strict"; // Attach the function to the window global object window.clickMe = function() { alert("it works!!"); }; });
After updating, refresh your module, clear your browser cache (critical—old JS files often stick around), and test the button again.
Solution 2: Use Odoo’s Native Event Binding (Recommended)
For a more maintainable, Odoo-compliant approach, avoid inline onclick handlers entirely and bind the event using Odoo’s framework. Here’s how:
- Update your XML button to remove the
onclickattribute and add a custom class:
<button name="test_js" string="Test Javascript File" type="object" class="btn-primary test-js-button"/>
- Modify your
test.jsto hook into the form controller and bind the click event:
odoo.define('myModule.test', function(require) { "use strict"; var core = require('web.core'); var FormController = require('web.FormController'); // Extend the FormController to add our button event FormController.include({ renderButtons: function($node) { this._super.apply(this, arguments); // Check if the button exists on the current form if (this.$buttons) { this.$buttons.find('.test-js-button').on('click', function(e) { e.preventDefault(); // Stop the default "object" type button action alert("it works!!"); }); } } }); });
This method follows Odoo’s best practices, keeps your code encapsulated, and avoids polluting the global scope.
Final Checks
- Make sure your XML file correctly loads the JavaScript module (you already had this working initially, but double-check the
<script>tag path). - Clear your browser cache (Ctrl+Shift+R on most browsers) to ensure the updated JS file is loaded.
- Update and upgrade your module in Odoo to apply all changes.
内容的提问来源于stack exchange,提问作者Tessnim

