我想在我的模板中使用模型实例中的值,在PHP中我会做以下几点:
<?php
class User {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
}
$localuser = new User("john doe");
?>
<p>My name is: <?= $localuser->getName(); ?></p>
但是我如何在Ember.js中这样做?或者我是否误解了Ember.js的MVC模型?
这是我用于创建localuser实例的Ember.js代码:
Example = Ember.Application.create();
Example.User = Example.Object.extend({
firstname: null,
lastname: null,
network: null,
fullName: function() {
return this.get('firstName') + " " + this.get('lastName');
}.property('firstName', 'lastName')
});
Example.LocalUser = Example.User.create({
firstname: "John",
lastname: "Doe"
});
Example.IndexRoute = Ember.Route.extend({
setupController: function(controller) {
},
renderTemplate: function() {
this.render("exampleTemplate");
}
});
and my HTML template (which doesn't work):
<script type="text/x-handlebars" data-template-name="exampleTemplate">
{{#model Example.LocalUser}}
{{fullName}}
{{/model}}
</script>
我需要在模板中放置什么才能从Example.LocalUser中获取fullname值来显示?
答案 0 :(得分:1)
您必须完成与PHP中几乎完全相同的操作:创建对象的实例。你几乎是对的,有一些错误:
Example.LocalUser = Example.User.create({...})
来创建实例,但这是Ember中的反模式。惯例是在应用程序命名空间中保留 classes ,例如Example.IndexRoute
,Example.User
等。但永远不要实例。模型对象是实例,将它们暴露给视图的最佳方法是使用model
或setupController
挂钩设置控制器。{{#model}}...{{/model}}
Handlebars助手。您可以使用控制器提供的变量:{{model}}
或仅{{controller}}
,如果您设置它,例如。在控制器的路线上。firstname
- &gt; firstName
:)鉴于上述情况,(推测)工作示例应该是:
<强> JavaScript的:强>
Example = Ember.Application.create();
Example.User = Ember.Object.extend({
firstName: null,
lastName: null,
network: null,
fullName: function() {
return this.get('firstName') + " " + this.get('lastName');
}.property('firstName', 'lastName')
});
Example.IndexRoute = Ember.Route.extend({
model: function() {
var user = Example.User.create({
firstName: "John",
lastName: "Doe"
});
return user;
},
renderTemplate: function() {
this.render("exampleTemplate");
}
});
<强>模板:强>
<script type="text/x-handlebars" data-template-name="exampleTemplate">
{{model.fullName}} - {{controller.fullName}}
</script>
<强>输出:强>
John Doe - John Doe