melanke / Watch.JS

watch the changes of any object or attribute
Other
2.14k stars 219 forks source link

question about using arrays of objects #123

Open edwardsmarkf opened 6 years ago

edwardsmarkf commented 6 years ago

hello -

if i were using an array of objects like this:

var obj = [
{
    id: 1,
    firstName: 'Mark Jones', 
    address: '123 Swallow Lane',
},
{
    id: 2,
    firstName: 'Lori Smith', 
    address: '948 South Elm Street',
}
];

WatchJS.watch(obj, (prop, action, newvalue, oldvalue) => {

is it possible to get the row number? this works great: obj[0].firstName='MARK'; // triggers alert with property, oldvalue and newvalue Is there any way to determine the changed row number, or perhaps the id value?

also, is there any way to watch for inserts and deletes?

thank you very much.

bonarja commented 6 years ago
var list=[
    {value:"test 1"},
    {value:"test 2"},
    {value:"test 3"}
]

watch(list,function(name,type,val,oldval){
    // get index
    var index = list.indexOf(this);

    console.log(index,name,type,val,oldval);
});

list[1].value="new value";
// 1 'value' 'set' 'new value' 'test 2'
slutske22 commented 3 years ago

I need to be able to do this too. Writing var index = list.indexOf(this); always returns a value of -1 for index and { get: [Function] } for this. Am I missing something? Can can I tell the index of the object that was changed in when watching an array of objects?