Manually Invoke IIFE

北慕城南 提交于 2019-12-27 03:35:26

问题


I've got a library (Hubspot Odometer) which I am using in a web application I am developing and it works fine to create and run Odometer style widgets on a page.

The trouble is that they are part of a dashboard interface which has panes that are loaded via AJAX. The initial view is not loaded via AJAX so the JavaScript executes fine and the odometers render correctly.

When I load a new pane with odometers however they are not rendered correctly nor do they act as they should. The reason for this is that the odometer library runs as one big IIFE.

What I am wondering is can I re-invoke the IIFE manually after I load content via AJAX so that the odometers are rendered and bound to correctly?

I am also using jQuery if that offers me any additional options.


回答1:


The whole idea of the IIFE is that its an anonymous function that is immediately executed. So by definition, no there is no way to re-execute it.

With that said however, you can store the function expression to a global variable, and execute it. For example

window.my_iife = (function() { /* stuff */ });
window.my_iife();

Notice the slight difference in syntax compared to the traditional IIFE: ((function() {})());

By storing the function in window, you are able to access it later from either the developer console or anywhere else in your code. If you simply store it in a var, or declare it as function my_iife() { /* ... */ } somewhere you risk that var or function declaration itself being wrapped in an IIFE and thus being inaccessible. As an example, that scenario could occur if the file you declared your var/function in is part of a Sprockets manifest (such as application.js in Rails).




回答2:


Try this:

var funcName = (function funcName() {
  // rest of the code
  return funcName;
}());

Also see this jsbin.



来源:https://stackoverflow.com/questions/32226040/manually-invoke-iife

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!