为什么变量替换不适用于我的情况?

时间:2019-01-24 16:44:21

标签: dojo

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

我可以看到该属性值在小部件内正在更新,但是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节点说“我的名字是罗伯特”,即新值,但是它永远不会更新。而是显示“我的名字是”。它不会覆盖默认值。

我确定我在某处缺少一个愚蠢的步骤,但是有人可以帮我弄清楚什么吗?

1 个答案:

答案 0 :(得分:0)

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

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

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

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

现在,name发生变化时,它将在您的innerHTML跨度内更改nameNode中的mySpan。如果您需要更多有关此绑定的信息,建议您检出the docs

希望这会有所帮助!

相关问题