2013-08-30 28 views
4

我的問題是:如何觀察像String或num這樣的簡單變量的變化? 我知道,你可以很容易觀察到的對象是這樣的:如何觀察飛鏢語言的簡單變量

observe(t, (e) => print ("Value changed")); 

,但如何做到這一點簡單的變量?

回答

2

observe包中包含單個可觀察值的包裝:ObservableBox

import 'package:observe/observe.dart'; 
import 'dart:async'; 

void main() { 
    ObservableBox myValue = new ObservableBox('hello'); 

    myValue.changes.listen((List<ChangeRecord> records) { 
    PropertyChangeRecord record = records[0] as PropertyChangeRecord; 

    print('${record.field} changed, it is now ${myValue.value}'); 
    }); 

    new Timer.periodic(const Duration(seconds: 1), (t) { 
    myValue.value = new DateTime.now(); 
    }); 
} 

沒有方法來觀察一個頂級或函數作用域的單字符串,布爾,int或雙不使用ObservableBox。

如果字符串,布爾值,整數或雙精度是類的字段,則可以使用ObservableMixin@observable批註。

class Foo extends Object with ObservableMixin { 
    @observable String bar = ''; 
} 

時富的實例變化然後就可以得到通知:

foo.changes.listen((List<ChangeRecord> records) { 
    // ... 
}); 
+0

看來,目前(SDK 1.6),它的名稱,而不是字段,屬性oldValue和NEWVALUE。然而,名稱是一個符號,所以record.name ==「myProperty」不會評估。人力資源管理。 –

+0

因此需要使用鏡像將record.name ==「myProperty」轉換爲字符串。看到我的答案和下面的代碼。 –

2

這裏是結合一個字符串值的一個例子是對象屬性:(該答案適用於Polymer.dart)

<!DOCTYPE html> 

<html> 
    <head> 
    <title>index</title> 
    <script src="packages/polymer/boot.js"></script> 
    </head> 

    <body> 
    <template id="_template" bind> 
     <input type="text" value="{{name}}"> 
     <p>The name is {{name}}</p> 
    </template> 

    <script type="application/dart" src="index.dart"></script> 
    </body> 
</html> 
import 'dart:html'; 
import 'package:polymer/polymer.dart'; 

class Person extends Object with ObservableMixin { 
    @observable 
    String name; 
    Person(this.name); 
} 

main() { 
    query("#_template").model = new Person('Bob'); 
}