【Odoo16前端源码分析】env变量

1 定义env变量

/* odoo/addons/web/static/src/env.js */

// -----------------------------------------------------------------------------
// makeEnv
// -----------------------------------------------------------------------------

/**
 * Return a value Odoo Env object
 *
 * @returns {OdooEnv}
 */
export function makeEnv() {
    return {
        bus: new EventBus(),
        services: {},
        debug: odoo.debug,
        _t: () => {
            throw new Error("Translations are not ready yet. Maybe use _lt instead?");
        },

        get isSmall() {
            throw new Error("UI service not initialized!");
        },
    };
}

2 创建env变量,并传给App

/* odoo/addons/web/static/src/start.js */

export async function startWebClient(Webclient) {
    ..

    // setup environment
    const env = makeEnv();
    await startServices(env);

    // start web client
    ..
    const app = new App(Webclient, {
        env,
        templates,
        dev: env.debug,
        translatableAttributes: ["data-tooltip"],
        translateFn: env._t,
    });
    ..
}
/* odoo/addons/web/static/lib/owl/owl.js */

class App extends TemplateSet {
    constructor(Root, config = {}) {
        ..
        const env = config.env || {};
        const descrs = Object.getOwnPropertyDescriptors(env);
        this.env = Object.freeze(Object.create(Object.getPrototypeOf(env), descrs));
        ..
    }
    ..
}

3 成为节点实例的component属性

/* odoo/addons/web/static/lib/owl/owl.js */
class ComponentNode {
    constructor(C, props, app, parent, parentKey) {
        ..
        const env = (parent && parent.childEnv) || app.env;
        this.childEnv = env;
        ..
        this.component = new C(props, env, this);
        ..
    }
..
}

this.component是视图类C(类View)的实例

/* odoo/addons/web/static/src/views/view.js */

export class View extends Component {
    setup() { .. }
    async loadView(props) { .. }
    onWillUpdateProps(nextProps) { .. }
}

但是View类没有构造函数,由父类Component来接管env参数

/* odoo/addons/web/static/lib/owl/owl.js */

class Component {
    constructor(props, env, node) {
        this.props = props;
        this.env = env;
        this.__owl__ = node;
    }
    setup() { }
    render(deep = false) {
        this.__owl__.render(deep === true);
    }
}
Component.template = "";

所以在this.component实例中,也能访问this.env属性

你可能感兴趣的:(Odoo,前端,javascript,odoo)