手动调用IIFE [英] Manually Invoke IIFE

查看:72
本文介绍了手动调用IIFE的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在Web应用程序中使用的库( Hubspot里程表)正在开发中,因此可以在页面上创建并运行Odometer样式的小部件.

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.

问题在于它们是仪表板界面的一部分,该面板具有通过AJAX加载的窗格.初始视图未通过AJAX加载,因此JavaScript可以很好地执行并且里程表可以正确呈现.

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.

当我用里程表加载新窗格时,它们无法正确渲染,也无法正常工作.这是因为里程表库是作为一个大型IIFE运行的.

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.

我想知道的是,在通过AJAX加载内容之后,可以手动重新调用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?

如果还提供其他选项,我也使用jQuery.

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

推荐答案

IIFE的整个思想是它的一个匿名函数可以立即执行.因此,根据定义,没有办法重新执行它.

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

请注意,与传统的IIFE相比,语法略有不同:((function(){})());

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

通过将函数存储在 window 中,您以后可以从开发者控制台或代码中的其他任何地方访问它.如果您只是将其存储在 var 中,或者将其声明为 function my_iife(){/* ... */} ,则可能会冒着 var 或函数声明本身包装在IIFE中,因此无法访问.例如,如果您在其中声明了 var / function 的文件是Sprockets清单的一部分(例如 application.js >在Rails中.

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).

这篇关于手动调用IIFE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆