arqex / freezer

A tree data structure that emits events on updates, even if the modification is triggered by one of the leaves, making it easier to think in a reactive way.
MIT License
1.28k stars 56 forks source link

Best way to set multiple fields #35

Closed aptheod closed 9 years ago

aptheod commented 9 years ago

Suppose i have two classes. On the first i set the frozen data...

var dataStore = new Freezer({
data: { 
array_1: [],
int_value: 0,
array_2: [],
bool_value: false
}
});

..and pass the dataStore.get().data as parameter on the constructor of the second one, on variable this.data. Now i want to assign some values to these fields. What's the best way to do it?

this.data = this.data.set({int_value: 5});
this.data = this.data.set({array_2: [1,2 ,3]});
this.data = this.data.array_1.append( [4, ,5 ,6] ); 

This way is working, since i don't have get() available, i have to assign to itself on every set. Is that correct?

thanks

arqex commented 9 years ago

Hi @aptheod

I would do something like

var data = this.data.set({ int_value: 5, array_2: [1,2,3] })
  .array_1.append( [4,5,6] )
;

But be aware of the data object returned, it will have the updated array_1 node, instead of the data one, because the last operation is made on this.data.array_1.

If you don't have access to the get() method to restore the data object, your best option is use transactions

var dataStore = new Freezer({
  data: { 
    array_1: [],
    int_value: 0,
    array_2: [],
    bool_value: false  
  }
});

var data = dataStore.get().data,
    trans = data.transact()
;

// trans is a mutable representation of data
// that holds all the changes in its children
trans.int_value = 5;
trans.array_2.reset([1,2,3]);
trans.array_2.append([4,5,6]);

// Run transaction
data = data.run();

console.log( data );
console.log( dataStore.get().data );

http://jsbin.com/noqikokiqa/2/edit

arqex commented 9 years ago

As a suggestion, always try to use freezer nodes directly from the store, and never keep local copies of them, like this.data. If the store gets updated your this.data won't, so your app will get out of sync.

aptheod commented 9 years ago

Thanks, for your detailed explanation. I used the transactions option and worked great!