Skip to content

Question #81

@richierob62

Description

@richierob62

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions