gpt4 book ai didi

javascript Bootstrap 策略

转载 作者:行者123 更新时间:2023-12-04 19:37:54 28 4
gpt4 key购买 nike

我正在处理的项目目前只有一个 Bootstrap 文件,用于初始化应用程序中的所有 javascript 对象。类似于下面的代码

if(document.getElementById('nav')) {
new navigation();
}

if(document.getElementById('search')) {
new search();
}

new carousel();

但我担心的是,无论出于何种原因,其中一行 JS 错误中的所有 JS 代码都不会执行,我们几乎会造成单点故障。

我有兴趣听听这个问题的替代方案和解决方案,以及任何其他可能有助于缓解这个问题的 Bootstrap 策略。

提前致谢

最佳答案

Check this fiddle.

对于自己滚动,如果可以使用 data- html 5 属性来指定 Bootstrap 关系。然后您的 Bootstrap 函数可以遍历它们并启动构造函数。

您还可以将 id 的映射对象映射到构造函数。我将在此处使用该示例。

假设标记与此类似:

<body>
<div id="navigation"></div>
<div id="search"></div>
</body>

定义您的 Bootstrap 映射,创建 Bootstrap 方法并调用它:

// Declare your bindings in an object
var bootstrapBindings = {
"navigation" : NavigationBootstrap,
"search" : SearchBootstrap,
"failure" : null
};

function bootstrap() {
var i, element, instance;

// Bind everything in the bindings
for(i in bootstrapBindings) {
if(bootstrapBindings.hasOwnProperty(i)) {
try {
element = document.getElementById(i);
if(element) {
instance = new bootstrapBindings[i](element);

// Nestable bootstrap calls
instance.bootstrap();
}
} catch(e) {
// Do something with error if you want
alert('Unable to bootstrap: ' + e);
}
}
}
}

bootstrap();

关于javascript Bootstrap 策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15797891/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com