Karl Brightman
Karl Brightman

Reputation: 11

Observing a property of a child view

I am trying to work out the best method of observing a property on another view instance within Ember. Currently I have the following code that does not seem to be working correctly. Looking at documentation I can't seem to find anything on whether or not observers will only work for self.

App = Ember.Application.create();

App.ApplicationView = Ember.View.extend({
  myProperty: false,
  observerFiredCount: 0,

  testObserver: function() {
    var count = this.get('observerFiredCount');
    this.set('observerFiredCount', count + 1);
  }.observes('myProperty'),

  buttonClick: function(event) {
    if(this.get('myProperty')) {
      this.set('myProperty', false);
    } else {
      this.set('myProperty', true);
    }
  },

  willInsertElement: function() {
    var button = this.$('a');
    button.click($.proxy(this.buttonClick, this));
  }
});

App.TestObserverView = Ember.View.extend({
  testObserverAcrossViews: function() {
    console.log('hello world');
  }.observes('App.ApplicationView.myProperty')
});

I guess theres 2 questions that would be helpful here.

1. Is it possible to observe a property on another object instance.

2. What path do I use to access a childview instance?

Any feedback would be greatly appreciated. I feel as though there could be a cleaner way to do this :)

Upvotes: 0

Views: 778

Answers (1)

ahawkins
ahawkins

Reputation: 1174

The answer to all your questions is that you're approaching the problem from the wrong perspective. Views are destroyed. They are short lived. They don't exist globally. You need a controller. Controller's are long lived and meant to be bound to. Instead of trying to observe a view, you should observe a controller.

So, when the click event happens on the view, set a property on the controller. Other parts of the application can bind to that property on the controller.

Upvotes: 1

Related Questions