Alexandre Mélard
Alexandre Mélard

Reputation: 12649

ember.js have view's function observes controller's property

I have written a view:

export default Ember.View.extend({
  select: null,
  modify: null,

  createSelect: function() {
    return new ol.interaction.Select();
  },

  onMapCreated: function() {
    this.select = this.createSelect();
    this.modify = this.createModify();
  },

  init: function() {
    this._super();
    this.get('controller').addObserver('olMap', this.onMapCreated);
  },
});

The view is added in a template related to a controller which has an olMap property. I need to wait for the olMap property to be instantiated before doing some work in my view.

The code above is kind of working, except that the this referenced in the onMapCreated function is the controller's instance and not the view's instance.

I'm quite sure I am doing something wrong in my application's design. I would like to separate the concerns and get the drawing part outside of the main controller. Should I use a component? Not sure because it's not going to be reusable...

I would love to have some directions here.

Upvotes: 0

Views: 177

Answers (2)

Alexandre Mélard
Alexandre Mélard

Reputation: 12649

Here is what I've ended up with:

My setup:

Ember : 1.10.0

Ember Data : 1.0.0-beta.16

jQuery : 1.11.2

Directory structure:

  • controllers:
    • map.js
    • map-draw.js
  • templates
    • map.hbs
    • map-draw.hbs
  • views
    • map.js
    • map-draw.js

in the template templates/map.js I use a render helper like this:

{{render "mapDraw" mapDraw}}

the renderer uses the controller controllers/map-draw.js and the view views/map-draw.js

content of the view map-draw.js:

export default Ember.View.extend({
  templateName: "mapDraw",
  classNames: ["map-draw"]
});

in the controller map-draw.js I am binding the map.js controller.

export default Ember.Controller.extend({    
  needs: ['map'],
  olMap: null,
  //...//
  init: function() {
    this._super();
    this.get('controllers.map').addObserver('olMap', this, function(sender) {
      this.set('olMap', sender.get('olMap'));
    });
  }
  //...//
});

Upvotes: 0

Alexandre Mélard
Alexandre Mélard

Reputation: 12649

After reading the manual in the API section, I came up with the solution. I post it here is someone needs it someday. Actually, all I had to do is add a parameter this to the addObserver method in order to change the context.

export default Ember.View.extend({
  select: null,
  modify: null,

  createSelect: function() {
    return new ol.interaction.Select();
  },

  onMapCreated: function() {
    this.select = this.createSelect();
    this.modify = this.createModify();
  },

  init: function() {
    this._super();
    this.get('controller').addObserver('olMap', this, this.onMapCreated);
  },
});

Upvotes: 1

Related Questions