ikesultan
ikesultan

Reputation: 195

How to run js function on element that appears dynamically with Ember?

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?

Upvotes: 0

Views: 129

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

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.

Upvotes: 1

Related Questions