dojo要求和范围

pgx2nnw8  于 2022-12-20  发布在  Dojo
关注(0)|答案(2)|浏览(319)

有人能给我解释一下为什么当drawSection被称为“这个”值时,它会成为全局范围吗?
有没有办法在这里使用require,而不必在我丢失它之前将小部件保存在另一个变量中?

define("my/TextBox", [
  "dojo/_base/declare",
  "dijit/form/ValidationTextBox"
], function(
declare, ValidationTextBox
) {

   function drawSection() {
      alert(this);
      require(["dojo/dom-construct"], function(domConstruct) {
         alert(this); // this = window
      });   
   };    

   return declare([ValidationTextBox], {
       postCreate: function() {
           this.inherited(arguments);            
           drawSection.call(this)
       }
   });
});
ar5n3qh5

ar5n3qh51#

使用dojo/_base/langhitch()函数来解决这个问题非常简单。
因为require(["dojo/dom-construct"], function(domConstruct) {....})内的函数引用全局上下文,
所以在当前上下文中使用lang.hitch函数(通过使用this),问题就解决了
这是一个Fiddle
及以上工作片段:

define("my/TextBox", [
	"dojo/_base/lang",
  "dojo/_base/declare",
  "dijit/form/ValidationTextBox"
], function(lang,
  declare, ValidationTextBox
) {

  function drawSection() {

    alert(this);

    require(["dojo/dom-construct"], lang.hitch(this,function(domConstruct) {

      alert(this); // this = window

    }));

  };
  return declare([ValidationTextBox], {
    postCreate: function() {
      this.inherited(arguments);
      drawSection.call(this)
    }
  });
  
});


require([
    "dojo/parser",
    "my/TextBox",
    "dojo/domReady!"
], function(
    parser,
    TextBox
) {
    
    // important: parse document after the ValidationTextBox was extended
    parser.parse(); 
    
});
<link href="https://ajax.googleapis.com/ajax/libs/dojo/1.8/dijit/themes/claro/claro.css" rel="stylesheet"/>
<script src="//ajax.googleapis.com/ajax/libs/dojo/1.10.4/dojo/dojo.js"></script>

<body class="claro">
<input type="text" data-dojo-type="my/TextBox" />,
</body>
jrcvhitl

jrcvhitl2#

您需要像这样使用dojo/_base/langlang.hitch

require(["dojo/dom-construct"], lang.hitch(this, function(domConstruct) {

        alert(this); // this = window

  }));

这是一个常见的结束问题。
See https://dojotoolkit.org/reference-guide/1.10/dojo/_base/lang.html#hitch
作为一个好的实践,我建议将drawSection方法放在小部件内部,并将dom-construct required放在顶部(在从postCreate调用它时,您将始终需要它,因此"按需" require是多余的)

define("my/TextBox", [
        "dojo/_base/declare",
        "dijit/form/ValidationTextBox",
        "dojo/dom-construct"
  ], function(declare, ValidationTextBox, domConstruct) {

  return declare([ValidationTextBox], {
        postCreate: function() {
              this.inherited(arguments);            
              this.drawSection()
        },
        drawSection: function() {
              alert(this);
              //domConstruct.whaever you want
        }; 
  });
  });

相关问题