Karlo E.
Karlo E.

Reputation: 23

Ember generated action or jquery onclick

I have an ember application which works fine. But user's interaction does some DOM insertion like below...

$(.test).append(<a {{action "getData"}}>Get Data</a>);

The problem is that Ember seems do not recognize that an action "getData" has been added to the DOM. Nothing is happening when I click the element. Any thoughts on this?

Another way I am trying to do is:

 //create the element
 $(.test).append(<a id="idnum">Get Data</a>);

 //make click listener
 $('#idnum').click(function(){
 console.log("get data");
}

my question is where should i place the code inside the component so the it can listen on the click event. Thanks.

Upvotes: 0

Views: 823

Answers (3)

Ember Freak
Ember Freak

Reputation: 12872

Like Lux suggested avoid DOM manipulation. I prefer the following approach,
if it is dynamic then you can consider wrapping DOM element as a new component and use component helper. find sample twiddle

In application.js

    export default Ember.Controller.extend({
      appName: 'Ember Twiddle',
      linksArray:[ Ember.Object.create({value:'Text to display',routename:'home'}),
                   Ember.Object.create({value:'Text to display2',routename:'home'})],
      actions:{
        addItem(){
           this.get('linksArray').pushObject(Ember.Object.create({value:'AddedDynamically',routename:'home'}));
        }
      } 
    });

in Application.hbs

<h1>Welcome to {{appName}}</h1>
<br>
{{#each linksArray as |item|}}
 {{component 'link-to' item.value item.route }}
{{/each}}
<button {{action 'addItem'}}>Add Item</button>
<br>
{{outlet}}
<br>
<br>

Upvotes: 1

Lux
Lux

Reputation: 18240

The first example can't work because ember does not analythe the Handlebars elements in the DOM, but rather parses your Handlebars template with HTMLBars, which is a full HTML parser, and then renders it manually by inserting elements, not text into the DOM.

However the second example is the way to go if you have to rely on external code that does manual DOM manipulation. And it does work. Checkout this twiddle.

This does work:

this.$('.target').append('<a id="idnum">Get Data</a>');

this.$('#idnum').on('click', () => {
    alert('clicked');
});

Just make sure that the DOM is ready. So do it in the didInsertElement hook or after the user clicked a button or so.

Upvotes: 1

Raj
Raj

Reputation: 342

You should do it in Ember way. Try handlebars {{#if}} helper to render an element dynamically.

{{#if canGetData}}
<a {{action "getData"}}>Get Data</a>
{{/if}}

Here you can set the value of the canGetData to true in the controller based on the users action.

Upvotes: 2

Related Questions