简体   繁体   中英

Ember JS nested component bubbling

I have created a fiddle of the problem here: http://jsfiddle.net/jcarmichael/gFTPN/2/

I have nested components with an Ember JS app.

When an event is triggered on a particular component, it sends its action to the next component, and that in turn sends an action to the controller.

During the event on the component, it modifies the value, and this is reflected in changes on the next component up and the controller.

The problem is that the change to the value appears to occur on the next component up and the controller only after the event has bubbled. Since in the controller I am saving the model, it means the model gets saved with an out-of-date value.

The question seems similar to this one: Ember: nested components events bubbling

I tried adding targetObject to the component as shown but this didn't seem to fix it.

App = Ember.Application.create();

App.ApplicationController = Ember.Controller.extend({
    value : 1,

    actions : {
        controllerAction : function() {
           // Value shown here is 1, even though it was incremented by the component below
           alert('Value is ' + this.get('value'));   
        }
    }
});

App.Com2Component = Ember.Component.extend({
    value : null,

    actions : {
        sendMe : function() {
          this.sendAction();
          return false;
        }
    }
});

App.Com1Component = Ember.Component.extend({

    value : null,

    click : function() {
       // Increment the value
       this.set('value', this.get('value')+1);  
       this.sendAction();
       return false;
    }
});

I'm not sure why you're experiencing this behaviour, but I would guess that Ember propagates events/actions immediately and runs their code immediately, before the runloop has had a chance to run and propagate changes to the bound values.

One solution: http://jsfiddle.net/a2XUY/

   self = this;
   Ember.run.scheduleOnce('afterRender', function(){self.sendAction()});

I've wrapped the sendAction in an Ember.run.scheduleOnce, which means it will only run after the next runloop has had a chance to propagate property updates through the application.

More reference: http://emberjs.com/guides/understanding-ember/run-loop/

One solution to this problem involves passing this.get('value') + 1 as a parameter to the this.sendAction() call. Essentially the click function becomes

click: function() {
  this.sendAction(this.get('value') + 1);
}

Hence, the action bubbles up holding the parameter you need before you save the model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM