mercredi 12 août 2015

Adding to array causes all items in array to be re-rendered

I have an (Ember-CLI) array which I am looping over to display the items of that array using a component. When I add and item to that array I would expect the new item to be rendered, but the existing items to remain unchanged. However, what I am seeing is that ALL items in the array are re-rendered.

I was under the impression that only the new / changed / deleted items should result in a re-render? Otherwise, that is potentially (as is the case in my app where we are rendering hundreds of complex items using a whole host of nested components) a lot of wasted processing and rendering time resulting in slow performance and pauses for the user.

Am I doing something wrong here? Or is this the expected behaviour for Ember?

This simple example shows the re-rendering clearly:

application.js

export default Ember.Controller.extend({

    data : Ember.A([]),

    actions :
    {
        addData : function()
        {
            var data = this.get("data");

            data.addObject({label:data.length});
        },
    }
});

test-component.js

export default Ember.Component.extend({

    getlabel : function()
    {
        var item = this.get("item");

        Ember.Logger.log("getlabel",item.label);

        return item.label + " " + new Date;

    }.property('item.label'),

});

application.hbs

<button {{action 'addData'}}>Add</button>

{{#each data as |item|}}

    {{test-component item=item}}

{{/each}}

test-component.hbs

{{getlabel}}

Each click of the button add's an object to the array, which application.bhs loops over to display the list. As you can see, the getLabel function is bound on item.label, so since this does not change as items are added, I would not expect this to be run again as items are added. However, as you will see from the logs and view the timestamp change on the screen, it is re-called and the component content re-rendered as items are added to the array.

See it in action here: http://ift.tt/1P6GMQU

So, in summary:

1) Why does Ember re-render the test-component for every item in data when I add a new item to data?

2) Is there a way to prevent it doing this so only inserted / deleted / replaced items are re-rendered?

Aucun commentaire:

Enregistrer un commentaire