作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试找出用于通过 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() ) });
或者有更简单的方法吗?我在这里缺少什么概念可以让生活更轻松?
最佳答案
由于您正在寻找“正确”的方式,因此这里有一些一般注意事项:
您不需要单例类(JavaScript 不是 Java)。只需将其设为全局 obj 或更好的函数即可。
$.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/
我想成为 Spark 纱客户(link)。是否需要安装hadoop?还是只安装 yarn 可以吗? (by this link) 最佳答案 No Spark不需要Hadoop即可运行。 Apache
我是一名优秀的程序员,十分优秀!