ember.jsember.js-view

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.


Solution

  • 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:

    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'));
        });
      }
      //...//
    });