JSFiddle 中的 Dijit 对话框立即启动 - 而不是 onClick

Dijit Dialog in JSFiddle launching immediately - not onClick

我正在努力让 Dijit 对话框为可重现的示例工作。我从 this JSfiddle 中获取了工作代码,并简单地尝试将其转换为一个命名函数以在整个示例中使用。

作者使用:

new Button({label: 'Show dialog', onClick: function() {
   //Create dialog programmatically here
}
});

但我将其更改为略有不同:

function launchSelectDialog(selectOptions) {
    //Create dialog programmatically here
}
registry.byId("default-launch", "onClick", launchSelectDialog(allOpts));

Here is my version. 不幸的是,这只会在加载页面时立即启动对话框,而不会在单击按钮时再次启动。

我检查了 JSFiddle 中的 NoWrap 选项。我对发生的事情没有其他线索。 如果您有任何想法,请提供帮助。

() 是一个 调用运算符 。您自己调用该函数,并将该函数的返回值设置为事件处理程序。如果你想重用函数,使用闭包:

function launchSelectDialog(selectOptions) {
    // the returned function will be used as the event handler
    return function() {
       // the passed `selectOptions` is remembered in this context
    }
}

另一种选择是:

registry.byId("default-launch", "onClick", function() {
   launchSelectDialog(allOpts);
});

在使用 registry.byId() 检索之前,您需要启动按钮小部件。 在你的代码中实际上 registry.byId("default-launch") 返回 undefined;

此外,registry.byId() 函数只接受一个 id,因此其他参数将被忽略。

要修复它,您应该正确启动一个 Button 实例并在 onClick 内声明 launchSelectDialog(allOpts),如:

  var myButton = new Button({
    label: "Default Options",
    onClick: function() {
      launchSelectDialog(allOpts);
    }
  }, "default-launch");

低于您脚本的固定版本。

http://jsfiddle.net/usm829jq/

require([
  "dojo/dom",
  "dijit/Dialog",
  "dijit/form/Button",
  "dijit/layout/BorderContainer",
  "dijit/layout/ContentPane",
  "dijit/registry",
  "dojo/domReady!"
], function(dom, DijitDialog, Button, BorderContainer, ContentPane, registry) {

  var allOpts = [{
    label: "Foo",
    value: "foo"
  }, {
    label: "Bar",
    value: "bar"
  }]

  var myButton = new Button({
    label: "Default Options",
    onClick: function() {
      launchSelectDialog(allOpts);
    }
  }, "default-launch");


  function launchSelectDialog(SelectOptions) {
    var layout = new BorderContainer({
      design: "headline",
      style: "width: 400px; height: 400px; background-color: yellow;"
    });

    var centerPane = new ContentPane({
      region: "center",
      style: "background-color: green;",
      content: "center"
    });

    var actionPane = new ContentPane({
      region: "bottom",
      style: "background-color: blue;"
    });

    (new Button({
      label: "OK"
    })).placeAt(actionPane.containerNode);
    (new Button({
      label: "Cancel"
    })).placeAt(actionPane.containerNode);

    layout.addChild(centerPane);
    layout.addChild(actionPane);
    layout.startup();

    var dialog = new DijitDialog({
      title: 'dialog title',
      style: {
        //width: '400px',
        //height: '400px',
      },
      content: layout
    });

    dialog.containerNode.style.backgroundColor = "red";
    dialog.startup();
    dialog.show();

  }
})

有几个问题。

1) 就像其他人指出的那样,您正在调用函数而不是使用函数设置事件。因此对话框在加载时可见。

2) 您需要等待 html 解析完成。或者你需要使用 parser.parse()

这是更新后的提琴手:http://jsfiddle.net/49y3rxzg/9/