What is the correct way to subscribe to model events in a view?

I want to subscribe to a model that appeared as Invalid and became anError, so I can set some error state. I can think of two ways, both have their drawbacks.

The first way I can think of is using observers to create my own readInvalid and foundError attributes on the view:

becameInvalid: function() {
  var isValid = this.get('controller.model.isValid');
  if (Ember.isNone(isValid) || isValid) {
    return;
  }
  console.log('becameInvalid');
}.observes('controller.model.isValid')

becameError: function() {
  var isError = this.get('controller.model.isError');
  if (Ember.isNone(isError) || !isError) {
    return;
  }
  console.log('becameError');
}.observes('controller.model.isError')

      

This works, but uses a lot of templates. The second way I can think of is to add handlers to events after the model has loaded:

didLoad: function() {
  var isLoaded = this.get('controller.model.isLoaded');
  if (Ember.isNone(isLoaded) || !isLoaded) {
    return;
  }
  var model = this.get('controller.model');
  model.on('becameInvalid', function() {
    console.log('becameInvalid');
  });
  model.on('becameError', function() {
    console.log('becameError');
  });
}.observes('controller.model.isLoaded')

      

The problem with this approach is that it still requires some boilerplate code and (correct me if I'm wrong) event handlers won't be automatically cleared when the view is deleted.

What I would like to do is something similar to an observer protocol for events to be automatically cleaned up by the framework. For example:.

becameInvalid: function() {
  console.log('becameInvalid');
}.eventHandler('controller.model.becameInvalid')

becameError: function() {
  console.log('becameError');
}.eventHandler('controller.model.becameError')

      

Is there something like this?

+3


source to share


1 answer


I think your first suggestion is an acceptable solution. Here's his version, it's a little less detailed:

isValid : Ember.Computed.alias("controller.model.isValid"),
becameInvalid: function() {
  if(this.get("isValid"){
     return;
  }
  console.log('becameInvalid');
}.observes('isValid')

      



For details on Ember.computed.alias see this question . Also, I have not found a way to run observers only under certain circumstances (= only when isValid turns false) with the out-of-the-box Ember functionality. You will have to implement such an observer yourself.

0


source







All Articles