Using Ember.js and Handlebars, what is the differe

2019-05-17 08:40发布

Case I.Binding template to instance of view.

For example, let's say I have a template:

    <script type="text/x-handlebars" data-template-name="instance-template">
        <b> Name: </b> {{ name }}
    </script>

I can then bind an instance of view to it and append to the document ( for simplicity sake the param name is declared in view, as opposed to binding to some control layer) :

App.instanceView = Ember.View.create({
    templateName: 'instance-template',
    name: 'hello world'
}).append();

What exactly is going on behind the scenes here? By specifying a template name, is this instance of view somehow taking a template and compiling it with the parameters passed in the background?

Case II. Binding template to class view, template not named.

If, however, I want to bind a template to a class view such as:

App.ViewClass = Ember.View.extend({
    name: 'hello world',
});

The documentation uses a template of this form:

<script type="text/x-handlebars">
    {{ #view App.ClassView }}
        This part renders: {{ name }} 
    {{ /view }}
</script>

Please note, when I do this, for some reason this does not work. The quote 'This part renders: ' in the template actually renders, however the {{ name }} tag is not rendered. I have no idea why.

Case III. template bind to class view, template is named.

In addition, if I name the template above:

<script type="text/x-handlebars" data-template-name = 'class-template'>
    {{ #view App.ClassView }}
        This part renders: {{ name }} 
    {{ /view }}
</script>

and change the view to

App.ViewClass = Ember.View.extend({
    templateName: 'class-template',
    name: 'hello world',
});

nothing renders at all. Again I do not see what is going on here.

1条回答
一纸荒年 Trace。
2楼-- · 2019-05-17 09:01

Case 1 Yah pretty much. The view is rendering (and we are assuming the context is the view) then when we see {{name}} this will be equivalent to instanceView.get('name').

Case 2 Anonymous templates do not change context. When you define a template inside of {{#view}} the context won't change. To get the view's context that was used with the {{#view}} helper you'll need to use view.name. For example:

App.ViewClass = Ember.View.extend({
    name: 'hello world',
});

<script type="text/x-handlebars">
    {{name}} <!-- lets pretend this is "something else" -->
    {{#view App.ClassView}}
        This part renders: {{name}} <!-- "something else" -->
        {{view.name}} <!-- "hello world" -->
    {{/view}}
</script>

Case 3 This example makes no sense and should probably have an assertion fail with Ember (non minified version). You are defining a view that uses a template, then inside that template rendering that same view again with an anonymous template. If this is you intended meaning could you please provide a use case because there is probably a much simpler way to go about waht you are trying to accomplish.

查看更多
登录 后发表回答