0

I'm working on an Ember project and I have a button that inserts some HTML tags into the DOM. I want to call a javascript function to run upon loading of those new DOM elements. Here's my code:

    <script type="text/x-handlebars" id="doc">    
       {{#if isEditing}}
          {{partial 'doc/editbox'}}
       {{/if}}
         ...
    </script>

The partial doc/editbox simply contains some html tags.

I've tried running the javascript as part of the click button event that initiate the insertion, but the js doesn't work because the DOM elements don't exist yet. I saw this post: How to Run Some JS on an Element in the Index Template in Ember.js RC2 which suggested using Ember.run.next, however that didn't work since the View 'Doc' originally appears without those additional DOM elements (until button is clicked). How do I get the javascript function to run at the correct time?

Community
  • 1
  • 1
ikesultan
  • 185
  • 2
  • 5

1 Answers1

1

add an observes in the controller

watchEditing: function(){
  if (this.get('isEditing')){
    Ember.run.scheduleOnce('afterRender', function(){
      //do it here
    });
  }
}.observes('isEditing')

additionally you could use render instead of partial and create an associated view, and run it in the didInsertElement of that view.

Kingpin2k
  • 47,277
  • 10
  • 78
  • 96
  • This worked like a charm. Why does it only work when I put that in the Controller and not the View? – ikesultan Dec 11 '13 at 04:57
  • You could put it in the view, just change it from isEditing to controller.isEditing. is that what you meant by view? – Kingpin2k Dec 11 '13 at 04:59
  • By View, I meant the code inside of Ember.View.extend({...}). Anyway, is there a reason why it should be in the controller as opposed to the view or does it not make a difference? – ikesultan Dec 11 '13 at 06:11
  • I just figured isEditing was in the scope of the controller, if you have a view I'd probably tie it up there, both are fine tho – Kingpin2k Dec 11 '13 at 15:48