Search code examples
javascriptviewcontrollerember.js

How can i manipulate dom in controller in emberjs?


Here is a scenario:

I load data when controller is init. And when loading is finished. I want to resize the container element's size according the load data. So here is the problem, how can i access the view in a controller?

I know i can manipulate dom in view by this.$() but how can i access dom in controller or how can i access view in controller. I use Ember.Router here. So i dont create view and controller manually.

http://jsbin.com/oxudor/edit#javascript,html I show some code sample here. The code can not be executed, but it can show my problem. I did some comments on the code where have the problem.


Solution

  • I think you should not play with dom in the controller. That breaks MVC. Perhaps one solution could be to define an observer in the view, listening to the content of the controller. In this observer, then play with the dom (you're in the view, so no problem). As @pangratz suggests, with some code, perhaps I can give you a more complete answer.

    EDIT: I think you could put the carousel function in the related view, and observes the controller.loading property. Here you could retrieve the jquery object of the view by using this.$().

    carousel: function() {
      var context = this.get('controller'), 
          self = this;
    
      if(context.get('loading') === false) {
        setTimeout(function() {
          var width = self.$('#page_wrapper').width(),
              num   = self.$('.page').size();
          self.$('#pages').width(width * num);
          self.$('.page').width(width);
          console.log([width, num]);
          console.log(context.get('elements'));
        }, 100);
      }
    }.observes('controller.loading')
    

    Hope this help...