omniscientjs / immstruct

Immutable data structures with history for top-to-bottom properties in component based libraries like React. Based on Immutable.js
374 stars 21 forks source link

Question #81

Open richierob62 opened 9 years ago

richierob62 commented 9 years ago

I'm new to using github, so please forgive me if this is in the wrong place. I couldn't find anywhere else to pose the question.

I'm loving immstruct, but not for the life of me can I figure out how to create a cursor for an object within a collection/array. I have the following:

var structure = immstruct({
    catalog: [],
    cartItems: [],
});

// populate catalog for now...
for (var i = 1; i < 9; i++) {
    structure.cursor('catalog').push({
        'id': 'Widget' + i,
        'title': 'Widget #' + i,
        'summary': 'This is an awesome widget!',
        'description': 'Lorem ipsum dolor sit amet consectetur adipisicing elit. Ducimus, commodi.',
        'img': '/assets/product.png',
        'cost': i
    });
}

// My _increaseItem function accepts an index; is this the way I should be getting
// the index?  By casting the cursor of the collection to an array and then
// using indexOf()?
function _addItem(item) {
    if (!item.inCart) {
        item['qty'] = 1;
        item['inCart'] = true;
        structure.cursor('cartItems').push(item);
    } else {
        var cartArray = structure.cursor('cartItems').toArray();
        var itemIndex = cartArray.indexOf(item);
        _increaseItem(itemIndex);
    }
}

// Because I have no idea how to create a cursor to the actual entry,
// I am changing its value and then calling forceHasSwapped()
// Is there a better way?
function _increaseItem(index) {
    var item = structure.cursor('cartItems').get(index);
    item.qty++;
    structure.forceHasSwapped();
}

Thanks in advance Richard