【问题标题】:Attaching a Widget at a specific node在特定节点附加 Widget
【发布时间】:2015-10-16 09:08:09
【问题描述】:

每当我初始化一个新的小部件时,我都需要将一个自定义小部件添加到特定的 div。

我相信最标准的方法是使用链接

 (new MyFirstWidget()).placeAt('myDiv');

我对这种方法并不是很热衷,因为它在每次初始化时都需要placeAt() 的详细信息,而在我的情况下,我需要始终强制将该类型的小部件嵌套在特定的 div 中。

相反,我想在小部件类中添加此信息。

目前我正在使用以下代码,在postCreate() 中使用placeAt() 工作正常。

我想知道:

  1. postCreate() 是正确的地方吗?可以在更好的地方添加 在小部件生命周期内?
  2. 我注意到在postCreate() 中调用this.placeAt() 之前,小部件被标记为rendered,但实际上有 没有被渲染,因为还没有被添加到 DOM 中……为什么 是吗?

  define([
        'dojo/_base/declare',
        'dojo/dom-construct',
        'dijit/_WidgetBase',
        'dijit/_TemplatedMixin',
        'dojo/text!./templates/PanelBasic.html'
    ], function (
        declare,
        domConstruct,
        _WidgetBase,
        _TemplatedMixin,
        template
        ) {
        'use strict';
        var attachTo = 'myPanels';
        return declare([_WidgetBase, _TemplatedMixin], {
            templateString: template,
            ntvType: 'Panel',
            constructor: function () {
            },
            postCreate: function () {
                this.inherited(arguments);
                this.placeAt(attachTo);
            }
        });
    });

【问题讨论】:

    标签: javascript dojo


    【解决方案1】:

    postCreate 似乎是生命周期中的合适点。不过,您可能不想忘记先在其中致电this.inherited(arguments)

    _rendered 标志在 dijit/_TemplatedMixin 内部,在 buildRendering 运行后设置为 true,它负责从小部件的模板创建 DOM 元素。从这个意义上说,它已经被“渲染”了(从模板字符串到 DOM),虽然它还没有在文档流中。

    【讨论】:

    • 感谢您的回答,我添加了提到 this.inherited() 的问题
    • 只是一个简单的问题,不相关,通常在 costructor() 和 this.preamble() 中使用 this.inherited(arguments) 吗?感谢您抽出宝贵时间。
    • declare 默认情况下已经链接了构造函数,所以你不应该在那里调用inheriteddeclare 实际上会警告它)。据我所知,这只是constructor 的具体情况。
    • 我查看了方法 postCreate() 的 dijit._WidgetBase 的代码,我注意到该文件中没有实现。所以我可以问你......如果超类没有实现,为什么我应该在 postCreate() 方法中调用 this.inherited(arguments) ?我注意到 this.inherited(arguments) 在按类使用“严格模式”时会产生一些问题,请在此处查看 stackoverflow.com/questions/33208956/… 感谢您在这方面的专业知识。
    • _WidgetBase_TemplatedMixin 不实现 postCreate,所以如果您继承这些,那么当然,您不需要调用 @ 987654334@ 在里面。然而,其他各种小部件确实实现了postCreate,因此根据经验,最好不要忘记调用inherited,以免意外破坏/破坏现有功能。同时,declare 本质上与严格模式不兼容,因为它访问的调用者链在严格模式下是不允许的。
    猜你喜欢
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 2016-12-15
    相关资源
    最近更新 更多