2017-04-27 46 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

相关问题