道场要求和范围

时间:2017-02-22 14:03:05

标签: javascript dojo

任何人都可以向我解释为什么在drawSection被称为“{1}}这个'价值成为全球范围?

无论如何在这里使用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)
       }
   });
});

2 个答案:

答案 0 :(得分:2)

退出简单使用dojo/_base/lang hitch()功能来解决问题。

因为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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您需要使用dojo/_base/lang lang.hitch,如下所示:

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

        alert(this); // this = window

  })); 

这是一个常见的封闭问题 见https://dojotoolkit.org/reference-guide/1.10/dojo/_base/lang.html#hitch

作为一种良好做法,我建议在窗口小部件中使用drawSection方法,并在顶部需要dom-construct(当您从postCreate调用它时,总是需要它,所以a “按需”要求是矫枉过正的)

  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
        }; 
  });
  });