dstore ( dojo ) event (add) misfiring on collection

200 views Asked by At

dojo version : 1.10.0

dstore version : 1.1.0

Steps that were followed.

1) Created a memory store using the dstore memory ( employeeStore ).

2) Created a collection salesEmployee by applying the filter.i,e employeeStore.filter({department:'sales'});

3) Added the add event listener on the salesEmployee collection.

4) Added a new employee to the employeeStore with department accounting i.e employeeStore.add({name:'William', department:'accounting'});

The add event listener fires even though it is attached to the salesEmployee collection.

As per my understanding event listener should not fire, since the employee belongs to the accounting department and the listener is attached to the salesEmplyoee collection.

Here is the jsfiddle.

require({
    packages: [
        {
            name: 'dstore',
    location: '//cdn.rawgit.com/SitePen/dstore/v1.1.0'
        }
    ]
}, [
    'dojo/_base/declare',
    'dstore/Memory',
    'dojo/domReady!'
], function(declare, DMemory ) {
    var employees = [
                        { name:'Jim', department:'accounting'},
                        { name:'Bill', department:'engineering'},
                        { name:'Mike', department:'sales'},
                        { name:'John', department:'sales'}
                    ];

    var employeeStore = new DMemory(
        {data:employees, 
         idProperty: 'name'});

    var salesEmployees = 
        employeeStore.filter({department:'sales'});

    salesEmployees.on('add', 
                      function(event){
                            alert(JSON.stringify(event.target));

                        });

    employeeStore.add({name:'William', department:'accounting'});

});

Is my understanding correct?

1

There are 1 answers

0
Ken Franqueiro On BEST ANSWER

Collections typically inherit the add/put/remove methods from the store they originated from. When dstore fires events, all collections related to the store are notified. This is largely for consistency's sake, since in cases where the store is server-based, it would be impossible to determine purely client-side whether each event is applicable to each collection depending on its range/filter/sort criteria. Admittedly, what is most consistent doesn't always prove to be most convenient for the simple cases that could feasibly filter events.

If you were to make your in-memory store trackable (using dstore/Trackable) and listen on a tracked collection, you should be able to distinguish between events for items matching your filter by checking event.index and event.previousIndex (both would be undefined for items that are filtered out).

var TrackableMemory = declare([ Memory, Trackable ]);
var store = new TrackableMemory({ data: ... });
var collection = store.filter(...).track();
collection.on(...);