0

My project requires to :

  • set values to global variable
  • then load external JavaScript which uses this global variable
  • then change variable and load again same javascript while the external javascript looks as (using Google Blockly):

    Blockly.Blocks[block_name+'_autogetter_state'] = {
        init: function() {
            this.setName(block_name);
        }
    };
    

and the global variable is block_name it seems that since i pass there variable it is only passed variable and not its value. So if I call the javascript twice and load it to some HTML, it seems that both blocks looks same.

probably the way I load the javascript is not important, I tried:

$('#htmlElement').append('<script src="' + jsURL + '" type="text/javascript"><\/script>');

and also via AJAX and then load it to HTML between <script> tag.

so the imported code then looks like:

<script> var block_name='';</script>
<div id="htmlElement">
      <script>
           block_name='A';
           Blockly.Blocks[block_name+'_autogetter_state'] = {
               init: function() {
                   this.setName(block_name);
               }
           };
           block_name='B';
           Blockly.Blocks[block_name+'_autogetter_state'] = {
               init: function() {
                   this.setName(block_name);
               }
           };
       </script>
</div>

while first block is with name = B and second also, while first should be A and second B. Fun part comes when you use the block with name A it works, so the system knows block with name A, but displays with name B.

It is also possible that while they are loaded asynchronously, the global variable is half filled with A and becomes B while the functions behind method .Blocks takes over and registers it as B...

But by now I want to make sure that there is no problem with passing global variable to imported javascript as I do... And am open to any suggestions since my creativity is pretty gone already with this case...

4

1 回答 1

1

可以使用数组和循环来避免代码重复并提高可伸缩性:

var block_names = ['A', 'B'];
block_names.forEach(function(block) {
  Blockly.Blocks[block + '_autogetter_state'] = {
     init: function() {
       this.setName(block);
     }
  };    
});

//编辑:block_name 在 setName fn 中阻塞。

于 2016-03-25T18:51:40.067 回答