Iga*_*lSt 6 javascript requirejs knockout.js
我的应用程序上有一个通用模块,用于从远程服务器检索数据,并具有get将检索到的数据导出到其他模块的方法.
让我们假设这个模块的名字是MyData:
define([], function(){
return function(opts) {
var data = null;
// go get data with ajax
var getData = function(){
$.ajax("getData").done(function(response){
data = response;
});
};
getData();
// return public api
if (arguments.length !== 0) {
var method = arguments[0];
switch (method) {
case "get": return data;
}
};
};
});
Run Code Online (Sandbox Code Playgroud)
问题是当我定义其他使用的模块时MyData,每次创建一个新实例MyData,导致它每次都从服务器检索数据.
我可以使用Web存储(或其他全局变量)来存储返回的数据,但这似乎是一个糟糕的解决方案.
有没有办法强制RequireJS只创建一次实例?
PS:
在我的项目中我使用KnockoutJS,data变量是ko.observable,所以也许淘汰赛可以解决我的情况?
RequireJS 已经加载了每个模块一次。你只需要稍微重构一下你的代码:
// myModule.js
define(function() {
// The dataFetch Promise will be initialized when this module
// is loaded for the first time.
var dataFetch = $.ajax("getData");
return {
getData: function () {
// Return the Promise interface and let callers use the
// .done, .fail etc. methods on it
return dataFetch;
}
};
});
Run Code Online (Sandbox Code Playgroud)
用法:
define([ "myModule" ], function (myModule) {
myModule.getData().done(function (data) {
// use the data
});
});
Run Code Online (Sandbox Code Playgroud)
通过使用 返回的 Promise 接口$.ajax,您可以确保对仅获取一次的数据进行异步访问。
顺便说一句,也许您想要实现的模式是模型。
| 归档时间: |
|
| 查看次数: |
2299 次 |
| 最近记录: |