gpt4 book ai didi

javascript - 模块模式回调实现

转载 作者:行者123 更新时间:2023-12-03 12:11:28 24 4
gpt4 key购买 nike

我正在使用 HTML/CSS/JavaScript 重写一个简单的应用程序,该应用程序使用间隔创建带有图像的动画,并且有一堆控制这些动画的按钮。

它正在扩展并变得非常困惑,逻辑与通过 jQuery 进行的 DOM 操作混合在一个 JavaScript 脚本文件中。

所以我决定使用模块设计模式。

根据我对应用程序的描述,模块的此回调实现是否存在问题?

或者通过模块实现?

在此示例中,声明私有(private)变量并通过公共(public) API 访问它们的最佳方法是什么? getter 和 setter ?它们真的有必要吗?我想编写可读的代码,但我不想过度架构。

(function($) {

$.Module = function(options){
var module = {
options: $.extend({
callbacks: {
start: false
}
}, options),
start: function(callback){
//console.log('private start method');
if(typeof callback === "function") {
callback();
}
}
}

// public api
return {
start: function(){
//console.log('public start method');
module.start(module.options.callbacks.start);
}
}
}

}($));

var myModule = $.Module({
callbacks: {
start: function(){
console.log('start callback!');
}
}
})

myModule.start();

Here是一个样本。

只是因为它似乎对我有用,而且我见过其他实现,它们的代码如下所示:

callback: function(method) {
if(typeof method === "function") {
var args = [];

for(var x = 1; x <= arguments.length; x++) {
if(arguments[x]) {
args.push(arguments[x]);
}
}

method.apply(this, args);
}
},

我不确定最后一段代码应该做什么。是否打算将数据返回到我实例化模块时注册的回调函数?如果是这样,它是如何工作的?

最佳答案

Is there a problem with this callback implementation for a module?

如果这就是你想要的,就不是。

Or with the module implementation?

您的 options 属性的实例化可能应该使用 deep extend ,当前的回调正在覆盖整个 callbacks 对象。

I'm not sure what this other code I found is supposed to do. Is it intended to return data to the callback function

是的。它确实支持多个参数,使用 arguments object

… I registered when instantiating the module?

不,这与注册无关。它将调用作为参数传递给此回调函数的方法

使用此代码将使您无需每次都进行 typeof 检查。你只需写

helper.callback(this.options.callbacks.start, /* optional arguments */)
// instead of
if (typeof this.options.callbacks.start == "function")
this.options.callbacks.start(/* arguments */)

但是,除非您认为需要这个帮助器,否则您将不需要这个帮助器。

关于javascript - 模块模式回调实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24944409/

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