How to add (remove) new items to an existing dataSource in Dashcode?

1.5k views Asked by At

I have a question concerning DashCode and dataSources: I have defined an JSON object in javascript file, linked it to a dataSource and connected the company names to the user interface (a 'list' element). The JSON object looks like:

{
    items: [
        { company:'A', product:'a1', color:'red' },
        { company:'B', product:'b2', color:'blue' },
        { company:'C', product:'c3', color:'white' }
    ]
}

How do I programmatically add (or remove) an additional "item" to the existing dataSource? I have used the following approach:

function addElement() {
    var newElement = [{company:'D', product:'d4', color:'yellow' }];
    var ds = dashcode.getDataSource('list');
    ds.arrangedObjects.addObject(newElement);
}

and

function delElement()
{
    var ds = dashcode.getDataSource('list');
    if (ds.hasSelection()) {
        var index = ds.selectionIndex();
        ds.arrangedObjects.removeObjectAtIndex(index);
    }
}

This piece of code indeed adds (removes) an additional item to the dataSource. However, when I use the list.filterpredicate to search the list for the new item, the new item is ignored.

What is the 'correct' approach to add (or remove) an item to an existing dataSource programmatically?

Your help is being appreciated!

1

There are 1 answers

0
gonzo007 On

Here is an answer to the question:

1) Define a KVO object in main.js. This step is important to make the object bindable:

anObj = Class.create(DC.KVO, {
    constructor: function(company, product, color) {
       this.company = company;
       this.product = product;
       this.color = color;
    }
});

2) The updated version of the function 'addElement' is:

function addElement() {
    var newElement = new anObj('D', 'd4', 'yellow');
    var ds = dashcode.getDataSource('list');
    var inventory = ds.valueForKeyPath('content');
    inventory.addObject(newElement);
}

3) The updated version of the function 'removeElement' looks similar:

function delElement()
{
    var ds = dashcode.getDataSource('list');
    if (ds.hasSelection()) {
        var index = ds.selectionIndex();
        var inventory = ds.valueForKeyPath('content');
        inventory.removeObjectAtIndex(index);
    }
}

I hope this information helps!