1

Sorry if this is redundant, but I've searched through several Q&A's here but I still can't figure out what I'm doing wrong. I have an array saved as a backbone collection, and I need to delete an object from that array using its index:

deleteCartItem:  function(e) {
    var itemIndex = $(e.currentTarget).attr( "data-index" );
    console.log(itemIndex)
    console.log(this.collection)
    console.log(this.collection.length)
    var newCollection = this.collection.splice(itemIndex);
    console.log(newCollection.length);

},

Here is my Backbone Collection:

[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]

1 Answer 1

2

splice actually modifies the collection, and returns the removed items. See the docs here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Try this instead:

deleteCartItem:  function(e) {
    var itemIndex = $(e.currentTarget).attr( "data-index" );
    console.log(itemIndex)
    console.log(this.collection)
    console.log(this.collection.length)
    this.collection.splice(itemIndex, 1);
    console.log(this.collection.length);

},

Also note the howMany parameter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.