emberjs / ember.js

Ember.js - A JavaScript framework for creating ambitious web applications
https://emberjs.com
MIT License
22.45k stars 4.21k forks source link

Cannot observe changes to nested properties on array using @each #541

Closed robharper closed 10 years ago

robharper commented 12 years ago

Adding an observer on a nested property of objects within a collection does not reliably fire. I've created a test case that could be added to ember-runtime/tests/mixins/array_test.js that illustrates this. Observing a nested property on the EachProxy itself appears to work fine. However, observing the property using @each.nest.isDone does not.

In the following test, count1 is incremented to 1, count2 is not:

test('modifying nested contents of an object in an array should call @each observers', function() {
  var ary = new TestArray([
      Em.Object.create({ nest: Em.Object.create({ isDone: false}) }),
      Em.Object.create({ nest: Em.Object.create({ isDone: false}) }),
      Em.Object.create({ nest: Em.Object.create({ isDone: false}) }),
      Em.Object.create({ nest: Em.Object.create({ isDone: false}) })
    ]);

  var get = Ember.get, set = Ember.set;
  var count1 = 0, count2 = 0;

  // Works
  var each = get(ary, '@each');
  Ember.addObserver(each, 'nest.isDone', function() { count1++; });

  // Doesn't work
  Ember.addObserver(ary, '@each.nest.isDone', function() { count2++; });

  count1 = count2 = 0;
  var item = ary.objectAt(2);
  get(item, 'nest').set('isDone', true);

  equal(count1, 1, '@each.nest.isDone should have notified - observing @each array');
  equal(count2, 1, '@each.nest.isDone should have notified - observing chain containing @each');
});
wagenet commented 12 years ago

@each is only supported one level deep. It would be nice to allow more, but I don't know how difficult this would be technically. I'll let @wycats or @tomdale chime in on this.

wycats commented 12 years ago

I don't think that's actually true... It uses the normal chain infrastructure and should work arbitrarily many levels deep.

wagenet commented 12 years ago

@wycats This sounds like a bug then. I've never seen it work more than one level deep.

tomdale commented 12 years ago

Agreed, this sounds like a bug. I believe this was working at some point. Thank you for the unit test.

endash commented 12 years ago

So I've been puzzling through this. It seems to boil down to EachProxy handling setting up the observers internally when you call addObserver with itself as the root. When as part of a chained path, however, the ChainNode plucks the top-level keyname off of the EachProxy, and goes on its merry way, and the EachProxy never gets involved. Basically, there are two levels of arrays at play.

watching '@each.nest.@each.isDone' DOES work, in this instance.

endash commented 12 years ago

Forgot to clarify that when the ChainNode plucks the keyname off the EachProxy, it's getting an EachArray, hence the need for nesting the @ each observers.

krisselden commented 12 years ago

The way chains work is each chain node has a corresponding chainWatcher that watches the key on the node's parent's value(), in order for this to work the chain needs to stop at @each and setup the chainWatcher with the remaining path.

I'm considering special casing @ character to just mean this.

wagenet commented 12 years ago

@kselden, does your simplify-properties branch touch on this at all?

wagenet commented 12 years ago

Looks like this is still an issue.

krisselden commented 12 years ago

chains do not chain through properties that produce arrays, this requires some changes I stated above, no I haven't done any work on it. It also is problematic @each itself changes when the array does.

tpitale commented 12 years ago

I've hacked around this, for anyone that is facing this issue (especially when using ember-data associations), by adding a property on one side of the association that checks the property in the other end of the association (in my case, isLoaded) and then using that after the @each. As I said, this is a hack. But until 1.1, it works for me.

drogus commented 12 years ago

@tpitale: could you show an example of such hack? I'm not sure what you mean by adding a property on other side of association.

@kselden @wagenet: I encountered something similar recently, but frankly I'm not sure if this is the same bug, could you take a look at this fiddle: http://jsfiddle.net/uErrd/4/ ?

tpitale commented 12 years ago

@drogus given the original example, there would be a nestIsDone property for the path nest.isDone. So you could observe @each.nestIsDone.

mspisars commented 11 years ago

would really love to see this in 1.0 not 1.1 :+1:

wagenet commented 11 years ago

@mspisars Me too, but I don't want to block 1.0 on things that are difficult to fix and non-essential.

darthdeus commented 11 years ago

last activity 4 months ago ... :+1:

wagenet commented 11 years ago

@mspisars, @darthdeus I would love to see it in 1.0 too. The issue is not about desire, it's about ability.

phammer commented 11 years ago

:+1: for 1.0: would be really useful to have this working.

pdwinkel commented 11 years ago

:+1: for 1.0

wagenet commented 11 years ago

Public Service Announcement: +1s do not provide development resources where they are lacking.

We've already agreed that we'd love to have this feature but it's very much non-trivial to support. It's certainly not something we'll block 1.0 on.

endash commented 11 years ago

Agreed with @wagenet these are non-trivial code paths that touch mission critical parts of ember.

HWest commented 11 years ago

Any updates on this? We have been trying to use this for a web app that's about to be used by a major Hotel chain and none of the workarounds seem to work. The only workable solution at this point is to redesign this part of the interface to make it simpler which is a shame. Any information would be greatly appreciated and thanks for all your great work.

joliss commented 11 years ago

It's a surprisingly hard problem. Part of the issue is that even if you implemented it or worked around it, updating a dependent array (which seems to be be the most common use case) would take O(n_2) time, which is a big problem even for fairly small datasets. To get it to be O(n), we'd need smarter array primitives to compose dependent arrays. There has been some_ work on this by Peter and others, and people are definitely interested in pushing it forward, but I wouldn't hold my breath.

Related: #1288, #2711.

For now I'd recommend generating the dependent arrays on the server, basically as "computed relationships".

tim-evans commented 11 years ago

Here's another fiddle demonstrating this issue: http://jsfiddle.net/3bGN4/268.

meelash commented 11 years ago

Example workaround, demonstrating nested @each:

https://gist.github.com/meelash/5785328

dandehavilland commented 11 years ago

If this is on the backburner, it would be helpful to note this behaviour in the API docs (maybe I missed it?) as it took me a while to find this ticket.

luxzeitlos commented 11 years ago

@dandehavilland Exactly! It should definitly be noted here: 'http://emberjs.com/guides/object-model/computed-properties-and-aggregate-data/'. "@each.goo.bar" is still not working, i've needed days to find this out.

joliss commented 11 years ago

Good idea. https://github.com/emberjs/website/pull/653

kingpin2k commented 11 years ago

But technically you can view nested properties, just not nested collections of properties, right?

works - flagpole and flag are singular

    schools.@each.flagpole.@each.flag

but should be

    schools.@each.flagpole.flag

\ doesn't work - flags is a collection**

    schools.@each.flags.@each.flag 
joliss commented 11 years ago

@kingpin2k No, I don't believe any of those work. They won't update correctly.

[Edit: maybe I'm wrong]

kingpin2k commented 11 years ago

@joliss here's a jsbin showing it. http://jsbin.com/IXalezO/11/edit

wagenet commented 10 years ago

@kselden is this something you're likely to work on any time soon?

wagenet commented 10 years ago

This is documented as not working. It would be great to add, but it's obviously difficult / not high enough a priority. If someone wants to work on it, we'd be happy to review a PR.

serhiisol commented 10 years ago

You can just add new computed property, which will contains only very nested object, which you're trying to observe. And @each will works correctly Use next method

  allTickets: function () {
    var sections = this.get('sections'),
      each = Ember.$.each,
      tickets = [];

    each(sections, function (i, section) {
      each(section.rows, function (j, row) {
        each(row.tickets, function (k, ticket) {
          tickets.addObject(ticket);
        })
      });
    });

    return tickets;
  }.property(),

  checkedCount: function () {
    ///custom logic
    return something;
  }.property('allTickets.@each.is_checked')

instead of

  checkedCount: function () {
    ///custom logic
    return something
  }.property('sections.@each.rows.@each.tickets.@each.is_checked')
Microfed commented 9 years ago

:+1:

panayi commented 9 years ago

This is so easy to miss in the guides. I believe it should issue a warning when a nested @each is found.

dowsanjack commented 9 years ago

Yea, I agree. It should at-least throw a warning :+1:

RobbieTheWagner commented 9 years ago

This is still an issue many years later, correct? Is there a supported workaround of some sort?

kingpin2k commented 9 years ago

Yes, you could always just build up computed properties at each level and watch the computed property instead of each property on each collection.

RobbieTheWagner commented 9 years ago

@kingpin2k I tried something like that, and it didn't work. Had to use .observes because the property never evaluated itself. There should really be some sort of built in Ember stuff to handle this, in my opinion.

kingpin2k commented 9 years ago

Here's an example: http://emberjs.jsbin.com/faximekico/2/edit You essentially need to aggregate the values at the mid level.

RobbieTheWagner commented 9 years ago

I understand how to do it, the properties just don't fire, so observes had to be used.

kingpin2k commented 9 years ago

Can you show me an example, properties are lazily loaded, so if you aren't actually attempting to get the properties, they won't "fire".

RobbieTheWagner commented 9 years ago

I never did an explicit .get to retrieve the property in question, I did have another computed property that was supposed to listen to it though. It seems that only an explicit get or use in a template makes them fire though, and not having another property observe them.

kingpin2k commented 9 years ago

Correct, properties are only calculated on demand, just watching a property doesn't mean the property should be calculated. Rightfully so, if no one wants to use the property, there is no need to calculate the property.

RobbieTheWagner commented 9 years ago

@kingpin2k so what is recommend in this case? We're not supposed to use observes anymore.

kingpin2k commented 9 years ago

My example shows how to accomplish the nested each dependencies without an observer. I don't recall anyone saying observers shouldn't be used anymore, but I don't religiously pay attention.

RobbieTheWagner commented 9 years ago

@kingpin2k your example uses a property, .property('model.books.@each.titles')

That gives me the same problem where it won't fire, as it is a property. I have another property that needs to observe that property.

alexspeller commented 9 years ago

@rwwagner90 the approach definitely works, I suspect there is another issue in your code causing this problem. Try posting a jsbin showing the problem to figure out what it is

kingpin2k commented 9 years ago

I might understand what you are getting at, could you modify my example to clarify though?