PatriotBob
PatriotBob

Reputation: 123

Looking for conditional sub view didInsertElement event... or something

I'm assuming I am missing something because so far any feature I've needed has been in ember.js, even if just undocumented. (Yay github)

So how exactly am I supposed to use jquery.ui with views that have conditional sub views?

So say this is my template

<ul>
    <li>Item 1</li>
    {{#if someBinding}}
    <li>Item 2</li>
    {{/if}}
    <li>Item 3</li>
</ul>

And in my corresponding view...

someView = Ember.View.extend({
    ...
    didInsertElement: function() {
        this.$('ul>li').button();
    }
    ...
});

So the problem with this is that the view will be rendered into the DOM with Item 1 & 3 and then call didInsertElement. So Item 2 will not be built properly.

And manually observing 'someBinding' will fire before the conditional view is added to the DOM as well, so that's no help.

So is there an event or some way I can call my jQuery once all views are in and binding synced?

Upvotes: 2

Views: 472

Answers (1)

Mike Aski
Mike Aski

Reputation: 9236

This solution works for a 'statical' rendering (stuff value set before rendering, and not changing...):

Handlebars

<script type="text/x-handlebars" data-template-name='app-view'>
    <ul>
        <li>Item 1</li>
        {{#if view.stuff}}
        <li>Item 2</li>
        {{/if}}
        <li>Item 3</li>
    </ul>
</script>​

JS

App.ApplicationView = Ember.View.extend({
    templateName: 'app-view',

    stuffBinding: 'App.stuff',

    didInsertElement: function () {
        this.$('ul>li').button();
    }
})

You where missing the scope view. in the view.

Working JSFiddle here: http://jsfiddle.net/MikeAski/H6MNj/


For a stuff value changing through the time, try decoupling the Item 2 rendering, and nesting it in a subview which will contain conditional display logic.

Handlebars

<script type="text/x-handlebars" data-template-name='app-view'>
    <ul>
        <li>Item 1</li>
        {{#view view.stuffView}}Item 2{{/view}}
        <li>Item 3</li>
    </ul>
</script>​

JS

App.ApplicationView = Ember.View.extend({
    templateName: 'app-view',

    didInsertElement: function () {
        this.$('ul>li').button();
    },

    stuffBinding: 'App.foo.bar',

    stuffView: Ember.View.extend({
        tagName: 'li',

        stuffBinding: 'App.foo.bar',

        isVisible: function() {
            var stuff = this.get('stuff');
            return stuff;
        }.property('stuff'),

        didInsertElement: function () {
            this.$().button();
        }
    })
})

JSFiddle updated @ http://jsfiddle.net/MikeAski/H6MNj/3/


Another possible approach would consist to render a list of item, which may vary, using a CollectionView (or each helper).

Let me know if you wish to have a sample.

Upvotes: 2

Related Questions