我需要实现一个类似仓储模式的对象,用于维护一系列项目列表。这个仓储看起来可能是这样的:
var repository = {
data: [],
getAll: function() {
return this.data;
},
update: function() { ... }
}
该 repo 数据的最终消费者将是某些组件。我考虑利用对 repo 数据数组的引用,以便在其发生更改时更新 DOM:
function ItemList() {
this.data = repository.getData();
when (this.data is changed) {
update the view
}
this.userInput = function() {
repository.update();
}
}
虽然它看起来很整洁,而且据说使用了合法的功能,但这真的是个好主意吗?我应该在存储库中使用观察者/通知吗?
var repository = {
...
onDataChange: function(callback) { ... }
}
这里有一个使用Angular的示例: http://jsfiddle.net/xen8m148/
repository
。在这种情况下,由于仓库实际上并不操作数据,也不依赖于数据,因此不存在真正的数据耦合问题。 - light