Sam
Sam

Reputation: 4339

Removing item from array doesn't refresh template

Using Ember, I have an object in my controller that looks like this:

ItemDetails: {
    Retrieved: '2016-07-09',
    User: 'someuser',
    Items: [
        {
            Name: 'Item',
            Price: 'value'
        },
        // snip
    ]
}

This is set in the controller init using this.set('ItemDetails', jsonObject).

The template is rendered as

{{#each ItemDetails.Items as |Item|}}
    {{Item.Name}}
    {{Item.Price}}

    <input type="button" {{action "Remove" Item.Name }} value="Remove" class="btn btn-primary" />
{{/each}}

The action for Remove is defined thusly:

    Remove: function(itemName) {
        var details = this.get('ItemDetails');
        var index = -1;
        for(var i = 0; i < details.Facets.length; i++) {
            if(details.Items[i].Name == itemName) {
                index = i;
                break;
            }
        }

        if(index > -1) {
            details.Items.splice(index, 1)
            this.set('Search', details);
        }
    }

Now using the Chrome debugger I can confirm that the array is correct and the correct item is being removed. Subsequent calls in also show the array internally looks like it should.

However, the template does not reflect this change, i.e. the Item is still shown along with it's remove button. What am I doing wrong that the template is not being updated?

Upvotes: 1

Views: 999

Answers (1)

phkavitha
phkavitha

Reputation: 847

There are certain public methods which should be used to modify the array so that changes are observable. Here is the link: http://emberjs.com/api/classes/Ember.MutableArray.html

In your case, looks like the logic is correct. However, instead of using .splice() you should use .removeAt(index). Or, there are other simpler ways to solve it like using .removeObject().

For example:

http://emberjs.jsbin.com/zezera/edit?html,css,js,output

Hope this helps. Thanks

Upvotes: 3

Related Questions