简体   繁体   English

javascript自定义侦听器-加载元素时

[英]javascript custom listener - when element is loaded

I have anonymous function where I wrapped all javascript code inside (main.js). 我有匿名函数,我将所有JavaScript代码都包装在了其中(main.js)。 I pass global variable to one of function inside. 我将全局变量传递给函数之一。 But the problem is that variable is created after main.js is loaded. 但是问题是在main.js加载后创建了变量。 I could use jQuery document ready, but I don't want to wait entire document to be loaded. 我可以准备使用jQuery文档,但是我不想等待整个文档被加载。

main.js main.js

(function(){
  function example(){
    alert(globalVariable)
  }
})();

and phtml file that is loaded after 和之后加载的phtml文件

<script>var globalVariable = 'example'</script>

Is there any way to create custom listener and when this is created example() should be forced? 有什么方法可以创建自定义侦听器,当创建自定义侦听器时,应该强制使用example()吗? Something like that (just as example to show what I need): 这样的事情(仅作为示例说明我需要什么):

main.js main.js

(function(){
  listen(mycustomlistener){
    function example(){
      alert(globalVariable)
    }
  }
})();

phtml file phtml文件

<script>
var globalVariable = 'example'
create listener(mycustomlistener)
</script>

Where is the trigger that you expect from? 您期望的触发因素在哪里? Is it triggered by you or from an event or from a change? 是由您触发还是由事件触发或由更改触发?

If it is listener/observer design u are looking for. 如果它是侦听器/观察者设计,那么您正在寻找。 You could implement your own or use the one available in backbone.wreqr 您可以实现自己的方法,也可以使用ribs.wreqr中可用的方法。

http://zen-and-art-of-programming.blogspot.in/2013/12/backbonewreqr-jumpstart.html http://zen-and-art-of-programming.blogspot.in/2013/12/backbonewreqr-jumpstart.html

Also from the above code even though you create a listener your example function wont be called since it is just a functon declaration inside and not the call ie make it 同样从以上代码中,即使您创建了侦听器,您的示例函数也不会被调用,因为它只是内部的functon声明,而不是调用即使它

var eventAggregator = new Backbone.Wreqr.EventAggregator(); 


//Subscribe for the event! 
eventAggregator.on('eventName', function() { 
     (function example(){
         alert(globalVariable)
     })();            //observe the call i ve made here which is absent in urs!!!
}); 


//Raise the event! 
eventAggregator.trigger('eventName');

You could also use jquery observer and observable 您还可以使用jquery观察者和可观察的

https://gist.github.com/addyosmani/1321768 https://gist.github.com/addyosmani/1321768

This should help you out in what you want. 这应该可以帮助您解决所需的问题。 http://jsbin.com/mugage/1/edit?html,js,output http://jsbin.com/mugage/1/edit?html,js,输出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM