gpt4 book ai didi

Ember.js - 如何插入 Controller ?

转载 作者:行者123 更新时间:2023-12-02 06:04:57 25 4
gpt4 key购买 nike

所以我对 Ember 文档的理解是, View / Controller /模型的模式如下:

[view] <- [controller] <- [model]

( View 消耗 Controller 消耗模型)

在我之前使用 Ember 的经验中,我会设置一个 View 来使用模型,如下所示:
{{#with blogpost}}
{{#view MyApp.BlogPostView contentBinding="this"}}
<h1>{{title}}</h1>

<p>{{content}}</p>
{{/view}}
{{/with}}

现在说我创建了一个 Controller :
MyApp.BlogPostController = Ember.BlogPostController.extend()

我在哪里初始化这个 Controller ?

查看 Ember 文档,如果 Controller 与路由关联,这似乎会自动发生,但是如果我只想要一个将 View 和模型联系在一起的临时 Controller 怎么办?这可能适用于我页面上的任意组件。

我是否负责实例化 Controller ?我应该使用某种 controllerBinding属性?它会用我的模型还是我的 View 自动实例化?

任何建议表示赞赏;我对 Ember 中的模型/ View 模式感到满意,但我在确定 Controller 适合的位置时遇到了一些困难。

最佳答案

Looking at the Ember docs, it seems like this happens automatically if the controller is associated with a route



这是正确的,与路由关联的 Controller 将在需要时由 ember 自动实例化。

but what if I just want an ad-hoc controller which ties together a view and a model? This could be for an arbitrary component on my page. Am I responsible for instanciating the controller? Should I use some kind of controllerBinding attribute? Will it be instantiated automatically with my model, or with my view?



有多种方法可以让您的任意 Controller 由 ember 自动实例化,而无需您自己动手。

对于示例,假设您有一个 Controller ,它与任何名为 LonelyController 的路由无关。 ,
App.LonelyController = Ember.ArrayController.extend({
content: ['foo', 'bar', 'baz']
});

方法一

假设您有一条路线并且您连接到 setupController , 如果您尝试在这里请求您 LonelyControllerthis.controllerFor('lonely');这将使 ember 为您实例化它:
App.IndexRoute = Ember.Route.extend({
setupController: function(controller, model) {
this.controllerFor('lonely').get('content');
// the above line will retrive successfully
// your `LonelyController`'s `content` property
}
});

方法二

另一种可能的方式来获取您的 LonelyController由 ember 自动实例化将通过定义与 needs 的依赖关系来实现。另一个 Controller 中的 API:
App.IndexController = Ember.ObjectController.extend({
needs: 'lonely',
someAction: function() {
this.get('controllers.lonely').get('content');
// the above line will retrive successfully
// your `LonelyController`'s `content` property
}
});

使用 needs API 你也可以做这样的事情:
App.IndexController = Ember.ObjectController.extend({
needs: 'lonely',
lonelysContentBinding: 'controllers.lonely.content',
someAction: function() {
this.get('lonelysContent');
// the above line will retrive successfully
// your `LonelyController`'s `content` property
}
});

还有一些上述方法的其他组合来获得您的 LonelyController自动实例化,但我想现在应该更清楚了。

最后一个提示:要了解 ember 在后台自动创建的内容,您还可以启用生成日志记录以在您的控制台中观察这一点,这非常有帮助,方法是:
var App = Ember.Application.create({
LOG_ACTIVE_GENERATION: true
});

希望它有帮助。

关于Ember.js - 如何插入 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18046309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com