[英]How to notify observer when an Object changes?
簡短版:即使Ember認為屬性沒有更改,有沒有辦法確保觀察者收到更改通知,無論如何?
通常,炭燼觀測器模式對我有用,但在這里我遇到了麻煩。 我不確定這是否是錯誤,其他問題或功能,但是有關此事讓我感到困擾。
在這種情況下,我會對某種形式的myinstance.fireNotificationsNoMatterWhat("cache")
感到非常滿意,但是我在代碼中找不到類似的東西。 有什么我想念的嗎?
下面的示例代碼顯示了該問題。
<!DOCTYPE html>
<html>
<head>
<title>emberjs notification test</title>
<!-- using current (at the time) version 0.9.5, from emberjs.com
starter kit. -->
<script src="jquery-1.6.1.min.js"></script>
<script src="ember-0.9.5.min.js"></script>
<script>
Test = Ember.Application.create({});
// I don't want an arrayproxy this time, and would be happy to find
// out if there is some form of ObjectProxy?
Test.cacheObject = Ember.Object.create({
"cache": {},
"add": function(key, value) {
// In other situations, I don't need
// propertyWillChange/propertyDidChange, but here
// I'm stuck, and I can't notify listeners when my
// cache changes, so I figured I'd try out
// these commands, which don't work, either.
this.propertyWillChange("cache");
var cache = this.get("cache");
cache[key] = value;
this.set("cache", cache);
this.propertyDidChange("cache");
},
});
// Contrived watcher.
Test.watcher = Ember.Object.create({
// One of the many ways I've tried to bind to the
// the object to get the observer to fire.
"cacheBinding": "Test.cacheObject.cache",
"obs": function() {
// Ideally, whenever I call Test.cacheObject.add in different call
// stacks I should be notified.
console.log("cache has changed:");
console.log(this.get("cache"));
}.observes("cache"),
});
setTimeout(function() {
// I get notified on the first add...
Test.cacheObject.add("hello", "world");
}, 500);
setTimeout(function() {
// ...but I will not get notified on the second, or any subsequent addition.
Test.cacheObject.add("and", "universe");
}, 1000);
</script>
</head>
<body>
<h1>emberjs notification test</h1>
<h2>Please open your console to see the console.log output.</h2>
</body>
</html>
編輯:似乎有短期解決此問題的方法,但是嘗試了我自己的“修復”,並嘗試了以下Roy的建議之后,我認為我的核心問題將無法解決,直到此增強功能請求得到忙碌者的厚愛。灰燼團隊。 如果最終可以給我ArrayProxy給我的東西,我可以等待。
好的,發現了問題,不,這不是錯誤。 發生的事情是Test.cacheObject.cache
設置為的哈希值沒有改變。 基本上,您並沒有將實際的哈希更改為另一個哈希……您只是在更改內存中同一哈希的屬性。
看一下這個jsFiddle的解決方案,但是簡短的版本,您只需要更改var cache = this.get("cache");
到var cache = {};
編輯:
由於必須保留數據,所以我唯一想到的另一件事就是將cache作為一個數組,並在觀察cache.@each
同時為其分配鍵/值對。 我已經更新了jsFiddle來顯示它。 希望這種解決方法對您要完成的工作有效。
編輯2:
現在請參閱jsFiddle。 睡了一會兒后,我想到了一個可以滿足您所有要求的解決方案。 哦,我不相信“沒有解決方案” ...每個問題都有解決方案!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.