Pic*_*els 0 javascript design-patterns coffeescript
我有一个处理数据的类。其他类可以给它它们的值,数据类将填充它们。
它看起来像这样:
class Data
constructor : ->
@products = null
populateProducts : (callback)=>
ajaxCall (data)=>
@products = data
callback()
allProducts : (list)=>
if @products?
list = @products
else
@populateProducts => allProducts list
Run Code Online (Sandbox Code Playgroud)
我面临的问题是我添加的每个方法都必须检查产品是否存在。所以我正在研究使这部分代码可重用的方法。
我尝试的一种方法如下:
productsCheck : (callback)=>
if @products?
callback()
else
@populateProducts => products callback
Run Code Online (Sandbox Code Playgroud)
使用这种方法我可以简化所有产品:
allProducts : (list)=>
@productsCheck => list = @products
Run Code Online (Sandbox Code Playgroud)
最后,我正在寻找能够实现以下功能的技术:“如果产品不存在,则从数据库中填充它们”。我可能在想这可能是一种已知的模式,所以如果是这种情况,有关它的信息也值得赞赏。
下划线的概念是_.memoize
它将缓存对 id 的函数调用的结果(即第一个参数)。
记忆化是一种易于实现的模式。
var memoize = function _memoize(f) {
var cache = {};
return function _intercept(arg) {
if (cache[arg]) return cache[arg];
return (cache[arg] = f.apply(this, arguments));
}
};
Run Code Online (Sandbox Code Playgroud)
您必须调整此模式以使其与回调异步工作。
为了完整起见,这里是_.memoize代码:
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
Run Code Online (Sandbox Code Playgroud)
Underscore 似乎接受 ahasher作为第二个参数,它将根据参数生成唯一的键。(默认为下划线标识函数)。
它似乎还可以使用 hasOwnProperty ,因此您可以使用恼人的键,例如toString和valueOf,这将在属性检查中标记为真。