ractivejs 观察 init 与 set/push/update
ractivejs observe init vs set/push/update
在此代码示例中,
在初始化时,每个元素都会触发 observe,即使是没有 "prices" 的元素,但不会触发任何其他方法,为什么?
var _deals = [
{
prices: [
{
id: 1,
deal_id: 1,
guests_from: 100,
guests_to: 200,
price: 250
}
]
},
{
prices: []
},
{} // this fires also, Why?
];
var deals = [], // app database
dealsGuy; // app instance
deals = _deals;
// create our app view
dealsGuy = new Ractive({
el: '#app_block',
template: '#app-template',
noIntro: true, // disable transitions during initial render
data: {
deals: deals
},
decorators: {
datepicker: datepickerDecorator
}
});
dealsGuy.observe('deals.*.prices', function (newValue, oldValue, keypath) {
console.log( 'observe', keypath );
if( newValue === void 0 || newValue.length <= 0 ){
this.set(keypath,[{}]);
}
});
dealsGuy.push('deals', {}); // does not fire 'deals.*.prices'
我猜这是由于在初始化和更新期间考虑事物的方式存在细微差别。
总是触发初始化观察(即使值为undefined
),而只有当值实际发生变化时才会触发更新。
在此代码示例中, 在初始化时,每个元素都会触发 observe,即使是没有 "prices" 的元素,但不会触发任何其他方法,为什么?
var _deals = [
{
prices: [
{
id: 1,
deal_id: 1,
guests_from: 100,
guests_to: 200,
price: 250
}
]
},
{
prices: []
},
{} // this fires also, Why?
];
var deals = [], // app database
dealsGuy; // app instance
deals = _deals;
// create our app view
dealsGuy = new Ractive({
el: '#app_block',
template: '#app-template',
noIntro: true, // disable transitions during initial render
data: {
deals: deals
},
decorators: {
datepicker: datepickerDecorator
}
});
dealsGuy.observe('deals.*.prices', function (newValue, oldValue, keypath) {
console.log( 'observe', keypath );
if( newValue === void 0 || newValue.length <= 0 ){
this.set(keypath,[{}]);
}
});
dealsGuy.push('deals', {}); // does not fire 'deals.*.prices'
我猜这是由于在初始化和更新期间考虑事物的方式存在细微差别。
总是触发初始化观察(即使值为undefined
),而只有当值实际发生变化时才会触发更新。