简体   繁体   中英

ractivejs observe init vs set/push/update

in this code sample, on init, observe is fired for each element, even ones without "prices", but does not fire on any other method, Why?

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'

I guess it's due to a subbtle difference how things are considered during initialization and updates.

The initialization observe is always triggered (even if the value is undefined ), while updates are only triggerred if the value actually changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM