2017-04-27 44 views
0

對於我的佈局我有一個組件需要在渲染完成後初始化,然後再次如果我的數據中有任何更改。如何確定我的ractive計算值是否已更改

這將工作的很好,但我依靠計算值爲每個客戶端篩選和更改輸出,並通過observe更改事件經常觸發。我做什麼:

let myRactive = new Ractive({ 
    el: '#clientContainer', 
    template: myTemplate, 
    magic: true, 
    modifyArrays: true, 
    data: {data}, //=> this is an awful lot of Data changing all the Time 
    computed: { 
     usefulData(){ 
      let tempdata = this.get('data'); 
      //=> a lot of rearranging, filtering and sorting 
      // to adapt the data only for this specific client 
      return tempdata; 
     } 
    onrender: function() { 
     initmyLayoutComponent() 
    } 
    }); 

於是,我就讓它這樣

myRactive .observe('usefulData', function (newValue, oldValue, keypath) 
    destroymyLayoutComponent(); 
    initmyLayoutComponent(); 
}); 

但這發射的)每次什麼data變化(即使是一些完全無關的usefulData) ,和b)在ractive提交DOM之前,組件被重新初始化爲提前。

有沒有一種方法可以只觀察計算出來的值,或者哪一種會更好 - 只是觀察計算值中的特定動作(如我想對添加/刪除的對象作出反應,但不反應更改的值)?

回答

1

那麼你可以做的是實際發送一個clientData obj到模板中,然後只能聽那些數據。

let myRactive = new Ractive({ 
 
    el: '#clientContainer', 
 
    template: '<div>{{clientData.name}}</div><input type="text" value="{{clientData.name}}" /><div>{{email}}</div><input type="text" value="{{email}}" /><div>Clientdata changed: {{cnt}}</div>', 
 
    magic: true, 
 
    modifyArrays: true, 
 
    data: { 
 
    name: 'hallo', 
 
    email: '[email protected]', 
 
    cnt: 0 
 
    }, //=> this is an awful lot of Data changing all the Time 
 
    computed: { 
 
    usefulData() { 
 
     let tempdata = this.get('name'); 
 
     // Create your own data obj 
 
     tempdata = { 
 
     name: 'world' 
 
     }; 
 
     // set it to the ractive context 
 
     this.set('clientData', tempdata); 
 
    } 
 
    }, 
 
    oninit: function() { 
 
    this.observe('clientData', function(newValue, oldValue, keypath) { 
 
     let cnt = this.get('cnt') 
 
     cnt += 1; 
 
     this.set('cnt', cnt); 
 
     console.log('listen only to the computed data'); 
 
    }, {init: false}); 
 
    this.get('usefulData'); 
 
    }, 
 
    onrender: function() { 
 
    // do something 
 
    }, 
 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/ractive/0.9.0-build-123/ractive.min.js"></script> 
 
<div id="clientContainer"></div>

+0

非常感謝。我會嘗試這種方法,並嘗試調整我的原始腳本。 – Torf

相關問題