重新处理动态加载的“小部件"的代码? [英] Reprocess code for a dynamically loaded "widget"?

查看:71
本文介绍了重新处理动态加载的“小部件"的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码在我的UI中加载图块或小部件".有时(如更改方向),我必须重新绘制图块.其中一些内容是由脚本加载事件生成的.在重画过程中,不会再次加载此事件.我该怎么做?

I have the following code that loads a tile, or "widget", in my UI. Occasionally (like on orientation change) I have to redraw the tiles. Some of the content is generated by a script load event. During the redraw, this event is not getting loaded again. How can I accomplish this?

//html
let $elTile = $('<div/>').appendTo($elContainer);
$elTile.load('tiles/' + tile.name + '/' + tile.name + '.html #' + tile.name + '-content');
//javascript
$.getScript('tiles/' + tile.name + '/' + tile.name + '.js');
//css
$('head').append( $('<link rel="stylesheet" type="text/css" />')
    .attr('href', 'tiles/' + tile.name + '/' + tile.name + '.css'));

这是其中一个切片脚本文件的样子:

And here is what one of the tile script files looks like:

window.addEventListener("load", function() {
    //do some stuff that may need to be called again on orientation change
});

我从诸如>

I see from questions like this and this that I probably can't just "unload and reload" the script, so is there another way to process the "tile initialization" script again?

方向更改只是一个例子,我希望能够在可能的情况下任意调用tile初始化脚本.

Orientation Change was just an example, I'd like to be able to call the tile init script arbitrarily if possible.

推荐答案

根据设备的支持和要求,您可以做一些事情.

Depending on your device support and requirements, you could do a few things.

可以通过在事件侦听器中添加orientationchange来解决此问题.

One would be to deal with this by also adding orientationchange to your event listener.

$(window).on('load orientationchange', function(){ /* run your code for both*/});

另一个选择是使用resize事件.

Another option would be to use the resize event.

中所述,前者是特定于设备的,因为所有浏览器的行为都不同.这帖子.

更新: 您还可以创建一个基于匿名事件的函数,可以使用事件作为触发器随意调用该函数.例如.

UPDATE: You can also create an anonymous event based function that you can call at will using your event as the trigger. For example.

$(window).on('myCustomEvent', function(){ /*whatever code you want to run at any time*/});

然后,您可以从所需的任何逻辑点触发此类事件:

Then you can trigger such event from any logic point you need:

if ($(window).width() < 1024){
   $(window).trigger('myCustomEvent');
}

这篇关于重新处理动态加载的“小部件"的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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