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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This worked like a charm. Why does it only work when I put that in the Controller and not the View?
You could put it in the view, just change it from isEditing to controller.isEditing. is that what you meant by view?
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?
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.