gpt4 book ai didi

javascript - 抽象 jQuery

转载 作者:数据小太阳 更新时间:2023-10-29 04:52:51 34 4
gpt4 key购买 nike

在这些谈话中 Nicholas ZakasAddy Osmani他们讨论了在构建大型 Javascript 应用程序时将外观模式用作沙箱的想法,以便将应用程序与底层基础库分离。

这种解耦理论上允许您切换出基础库,而无需重写您的应用程序模块。然而在实践中这似乎更难实现。

这个提议的架构有具体的实现,例如AuraJS .然而,从源代码来看,沙箱似乎仍然存在抽象漏洞,因为它从其某些方法返回了 jQuery 对象。

我并不特别关心 AuraJS,但更关心的是在不丢失太多功能的情况下尝试抽象像 jQuery 这样的库的一般概念。

举个例子,假设我的门面/沙箱有一个 dom 方法 .find(selector)。对于它可能返回的内容,我可以想到 3 个选项:

  1. 一个 jQuery 对象 - 这会将 jQuery 泄漏到使用模块中。

  2. 原始 dom 元素 - 失去功能,没有人真正愿意使用它!没有链接。

  3. 自定义的类似 jQuery 的包装器 - 可能相当复杂,但似乎是理想的解决方案。

所以我的问题是,如何在不丢失太多功能的情况下抽象出像 jQuery 这样的库,以便在将来的某个时候可以用最少的努力替换它?

最佳答案

这是一个使用模块作为架构的非常简单的例子:

<!DOCTYPE html>
<title>Module play</title>
<body>
<script>

// myCore provides all functionality required by modules
// Could use a library in here
var myCore = {

getContainer: function() {
// code in here to find a suitable container in which to put widgets
// This is where different client capabilities will be tested to ensure the
// widget behaves in it's user agent context - desktop, phone, tablet, pad, etc.

// very simple shortcut
return {
element: document.body,

// This function could use a general purpose library
add: function(widget) {
this.element.appendChild(widget.getElement());
}
};

},

// This function could use a general purpose library
getNewWidget: function() {
var element = document.createElement('div');

return {

getElement: function() {
return element;
},

display: function(text) {

// Tightly couple to itself or not?
this.getElement().innerHTML = '<em>' + text + '</em>';

// or
element.innerHTML = '<em>' + text + '</em>';
}
}
}
};

// Missing sandbox layer...

// Add a module - only uses myCore API (access should be controlled by
// the sandbox), does not deal with underlying library or host objects
(function() {

// Get a container to add a widget too
var container = myCore.getContainer();

// Create a widget
var widget = myCore.getNewWidget();

// Add the widget to the container
container.add(widget);

// Give something to the widget to display
widget.display('Hello World');

}());

</script>
</body>

因此您可以看到,在模块级别,您不关心宿主环境或底层库,您只是在编写普通的 ECMAScript。你可以变得非常防御并做类似的事情:

(function() {
var container, widget;

if (!myCore) return;

if (myCore.getContainer) { // Some would include an isCallable test too

container = myCore.getContainer();
}

// getWidget could be a method of container instead so that
// everything you need is either a method or property of container
// or widget
if (myCore.getWidget) {
widget = myCore.getWidget();
}

...
}

等等,所以一切都经过测试和检查。我省略了错误处理,但希望这个例子足够了。

关于javascript - 抽象 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16032440/

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