Ember.js绑定和模板

Ember.js Bindings and Templates

本文关键字:绑定 js Ember      更新时间:2023-09-26

我正在测试Ember.js的主要特性。根据提供的指南,下面的代码,使用简单的绑定和自动更新模板应该输出Hey there! This is My Ember.js Test Application!,但它输出的是Hey there! This is !

JS:

// Create the application.
var Application = Ember.Application.create();
// Define the application constants.
Application.Constants = Ember.Object.extend({
    name: 'My Ember.js Test Application'
});
// Create the application controller.
Application.ApplicationController = Ember.Controller.extend();
// Create the application view.
Application.ApplicationView = Ember.View.extend({
    templateName: 'application',
    nameBinding: 'Application.Constants.name'
});
// Create the router.
Application.Router = Ember.Router.extend({
    root: Ember.Route.extend({
        index: Ember.Route.extend({
            route: '/'
        })
    })
})
// Initialize the application.
Application.initialize();

HBS:

<script type="text/x-handlebars" data-template-name="application">
    <h1>Hey there! This is <b>{{name}}</b>!</h1>
</script>

我做错了什么吗?

当你从模板中引用视图的属性时,你必须在它前面加上view关键字。

所以尝试

<script type="text/x-handlebars" data-template-name="application">
  <h1>Hey there! This is <b>{{view.name}}</b>!</h1>
</script>

它应该工作。

哦,我忘记了一些东西,绑定是错误的,你必须引用一个对象而不是一个类。试着

Application.constants = Ember.Object.create({
  name: 'My Ember.js Test Application'
});

Application.ApplicationView = Ember.View.extend({
  templateName: 'application',
  nameBinding: 'Application.constants.name'
});