emberjs where should document ready functions go?

2019-07-05 05:01发布

问题:

I'm trying to attach a typeahead to a text input in one of my templates. Because Ember use's handlebars, jQuery's document ready function is not the place for the typeahead definition. Where is the proper place to put "template ready" code? I tried a controller but there was no response from the typeahead. I don't think the template was rendered yet.

App.PersonController = Ember.ObjectController.extend({

    isEditing: false,

    init: function(){
        this._super();

        $('.example-films .typeaheadcx').typeahead([{
              name: 'best-picture-winners',
              remote: 'http://twitter.github.io/typeahead.js/data/films/queries/%QUERY.json',
              prefetch: 'http://twitter.github.io/typeahead.js/data/films/post_1960.json',
              template: '<p><strong>{{value}}</strong> – {{year}}</p>',
              engine: Ember.Handlebars
        }]);
    },

    actions: {
        edit: function() {
            this.set('isEditing', true);
        },

        doneEditing: function() {
            this.set('isEditing', false);
        }
    }
});

回答1:

The correct place is didInsertElement of Ember.View.

For example:

Template

<script type="text/x-handlebars" data-template-name="foo">
  Hello world
</script>

View

App.FooView = Ember.View.extend({
  templateName: 'foo',
  didInsertElement: function() {
    console.log(this.$().text()); // will log 'hello world'
  }
});