【问题标题】:Why does variable substitution not work for my case?为什么变量替换不适用于我的情况?
【发布时间】:2019-01-24 16:44:21
【问题描述】:

我正在尝试使用模板创建自定义小部件,但变量替换似乎对我不起作用。

我可以看到小部件内的属性值正在更新,但 DOM 没有改变。例如,当我使用 get() 方法时,我可以看到小部件属性的新值。但是,DOM 永远不会改变它的值。

这是我的模板:

<div class="outerContainer">
    <div class="container">
        <span class="mySpan">My name is ${name}</span>
    </div>
</div>

现在,这是我的小部件代码:

define([
    "dojo/_base/declare",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
    "dojo/text!/templates/template.html",
], function (declare, _WidgetBase, _TemplatedMixin, template) {
    return declare([_WidgetBase, _TemplatedMixin], {
        templateString: template,
        name: "",

        constructor: function (args) {
            console.log("calling constructor of the widget");
            this.name = args.name;
        },

        startup: function() {
            this.inherited(arguments);
            this.set("name", "Robert");  // this does not work
        },

        postCreate: function() {
            this.inherited(arguments);
            this.set("name, "Robert");   // this does not work either
        },

        _setNameAttr: function(newName) {
            // I see this printed in the console.  
            console.log("Setting name to " + newName);
            this._set("name", newName);

            // I also see the correct value when I get()
            console.log(this.get("name"));  // This prints Robert
        }
    });
});

我期待 DOM 节点说“我的名字是罗伯特”,即新值,但它永远不会更新。相反,它显示“我的名字是”。它不会覆盖默认值。

我确定我在某个地方错过了一个愚蠢的步骤,但有人可以帮我弄清楚什么吗?

【问题讨论】:

  • 我们能看到创建小部件的代码/模板吗?只要this.namebuildRendering 时间设置为您想要的,您就应该可以使用,并且在创建小部件后您永远不需要更改名称。我想知道 name 属性是否来自创建小部件的 DOM 中的 data-dojo-props 属性。如果是这样,postMixinProperties 可能会更改它并覆盖您在构造函数中设置的内容。

标签: dojo


【解决方案1】:

您应该将属性绑定到 dom 中的该点。因此,您需要将模板更改为:

<span class="mySpan">My name is <span data-dojo-attach-point='nameNode'></span></span>

并且在您的小部件中,您应该添加此函数以在name 更改时绑定它:

 _setNameAttr: { node: "nameNode", type: "innerHTML" },

现在,当name 更改时,它会更改您的mySpan 范围内的nameNodeinnerHTML。如果您需要了解有关此绑定的更多信息,我建议您查看the docs

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2019-03-10
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多