Dojo can't programmatically concatenate djits?

2019-02-27 10:38发布

问题:

With this code:

var d = new dijit.Dialog({
    title: "Programatic Dialog Creation",
    style: "width: 300px",
});
var button1 = new dijit.form.Button({'label': 'one', 'onClick': function () {
        alert('one')
}});

var button2 = new dijit.form.Button({'label': 'two', 'onClick': function () {
        alert('two');
}});
d.attr("content", button1 + ' | ' + button2);
d.show();

Expected result: A dialog with with two buttons inside

Actual result: A dialog with the text

[Widget dijit.form.Button, dijit_form_Button_4] | [Widget dijit.form.Button, dijit_form_Button_5]

What am I doing wrong? What is the correct way to accomplish this task? I've tried dojo.place and dojo.query with no success.

回答1:

You are mixing up Dijit objects, DOM nodes and strings.

The corrent way to place Dijits into Dialog or any container widget is:

dojo.place(button1.domNode, d.containerNode);
dojo.place(button2.domNode, d.containerNode);
d.show();

Or you can call placeAt() method when creating Dijit object:

var button1 = new dijit.form.Button({'label': 'one', 'onClick': function () {
    alert('one')
}}).placeAt(d.containerNode);

You got your result because what basically happens is

d.attr("content", button1.toString() + '|' + button2.toString());

Also note inserting strings is possible this way:

var button1Html = dojo.create("div").appendChild(button1.domNode).parentNode.innerHTML;
var button2Html = dojo.create("div").appendChild(button2.domNode).parentNode.innerHTML;
d.set("content", button1Html + "|" + button2Html);

but it won't work, because it creates new DOM nodes that are not referenced in Dijit objects (buttons), so your events won't fire.