gpt4 book ai didi

jquery - 具有 AJAX 初始值设定项设计模式的 javascriptMVC 单例

转载 作者:行者123 更新时间:2023-12-01 04:20:22 25 4
gpt4 key购买 nike

我正在尝试找出用于通过 AJAX 调用初始化的单例的正确模式。这是我已经完成的工作的简化示例。

它按预期工作,但我有一种感觉这不是“正确”的方式,并且有某种方法可以将初始化程序的回调挂接到当前正在运行的ajax请求的成功调用中,并且我担心可能会有是数组方法的竞争条件。我走在正确的道路上吗?

var singletonObj;
$.Class("SingletonTest", {
init: function(onSuccess) {
if (singletonObj) {
if (singletonObj.ajaxLoaded) {
onSuccess(singletonObj);
}
else {
singletonObj.callbacks.push(onSuccess);
}
}
else {
singletonObj = this;
singletonObj.callbacks = new Array(onSuccess);
singletonObj.count=0;

$.ajax({
url: "/path/to/json/config",
method: "GET",
success: function (res) {
singletonObj.data = res.meta_data;
singletonObj.ajaxLoaded = true

singletonObj.callbacks.forEach(function(callback) {
callback(singletonObj);
});
}
});
}
},
counter: function() {
return this.count++;
}
});

new SingletonTest( function(obj) { console.log("First call: "+obj.counter() ) });
new SingletonTest( function(obj) { console.log("Second call: "+obj.counter() ) });
new SingletonTest( function(obj) { console.log("Third call: "+obj.counter() ) });

或者有更简单的方法吗?我在这里缺少什么概念可以让生活更轻松?

最佳答案

由于您正在寻找“正确”的方式,因此这里有一些一般注意事项:

  1. 您不需要单例类(JavaScript 不是 Java)。只需将其设为全局 obj 或更好的函数即可。

  2. $.Deferred是你的 friend 。 $.ajax 返回一个 promise 。

这是单例的功能模式:

// creates a lazy singleton from a factory function
function singleton(factory) {
var deferred;
return function() {
return deferred || (deferred = factory());
};
}

// declare your specific singleton
var SingletonTest = singleton(function() {
return $.ajax({
url: "/path/to/json/config",
method: "GET"
}).pipe(function(obj) {
// pipe lets you modify the result
// here we add the counter method
var count = 0;
obj.counter = function() {
return count++;
};
return obj;
});
});

// use it
SingletonTest().then(function(obj) {
console.log("First: "+obj.counter());
});

SingletonTest().then(function(obj) {
console.log("Second: "+obj.counter());
});

如果您发现自己经常使用此模式,则有 JMVC plugin (披露:我是主要作者)实现了依赖注入(inject)的函数形式。

如果您要使用 Inject ,它看起来像这样:

var cache = Inject.cache();
var Injector = Inject(
cache.def('SingletonTest',function() {
return $.ajax({
url: "/path/to/json/config",
method: "GET"
}).pipe(function(obj) {
var count = 0;
obj.counter = function() {
return count++;
};
return obj;
});
})
);

var logCount = Injector('SingletonTest',function(obj,message) {
console.log(message+obj.counter());
});

logCount("First:");
logCount("Second:");

对于具有大量单例或只是延迟数据的大型项目,注入(inject)的规模比全局变量更好。

关于jquery - 具有 AJAX 初始值设定项设计模式的 javascriptMVC 单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11166839/

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