0
votes

I have an ember app which had code like this:

App.AccountListingsView = Ember.View.extend({
    didInsertElement: function() {

        console.log('did this fire');

    }
});

Every time I transition into this view, it fires whatever is in the didInsertElement (This works fine) However... after loading the view, I'd like it to fire only once. I don't need it to fire every time I go back to this page/view.

Is there a better way to execute code so that it fires once after a view is rendered, and not again when you navigate off of that view and back to it again? As of now, if I go into another view and back to the listings view it fires again in the console.

1
You can (and should) safely place jQuery selectors within didInsertElement. The bindings will be unique to each instance of the view, just in case it's destroyed and re-rendered upon transition, as you are suggesting. - Matthew Blancarte
The problem I want solved for example is if I have this inside didInsertElement: $('ul').append('<li />'); it will fire again once I leave the view and go back... meaning I will have 2 li's on the page, I only want the jQuery code to fire once, similar to on ready, but I can use it in the on ready because the view may not be rendered yet. - Matt
Why would you manually append DOM elements like that? You need to integrate that sort of logic into the handlebars templates or a component or something. - Matthew Blancarte
It's an example, I'm just wanting to know how to run code only once in didInsertElement... so that when I switch views and go back, it doesn't run the same code again. Unless there is something else one can use besides didInsertElement - Matt
Ember is really going to require you to understand MV* and you'll have to drink the Kool-Aid to make use of the framework. Arbitrarily attaching list items to all lists on the page obviously doesn't conform to any real useful logic... So "run-once" isn't as simple as you may be thinking. Yes, it will run-once, but there is a chance that the view will be destroyed and Ember will re-render a brand new unique DOM element for the view. Thus, you need to follow convention. - Matthew Blancarte

1 Answers

0
votes

No you can't. Wen transitioning the view gets destroyed and recreated when you come back. This will always get fired.

It's better to condition your actions based on some controller state.