我知道如何通过特定属性(this.findBy(prop, value)
)查找项目。我知道如何从底层数组模型中获取裸项(this.get("model")[index]
)。
但是,如果我引用了ArrayController,如何在特定索引处获取完整的ItemController包装模型?
为了更清楚,这是一个展示我需要的扩展颜色数组示例。
App = Ember.Application.create();
App.Router.map(function() {
// put your routes here
});
function color(name, value) {
return Ember.Object.create({name: name, value: value || name});
}
App.IndexRoute = Ember.Route.extend({
model: function() {
return [
color("red"),
color("green"),
color("yellow"),
color("purple")
];
}
});
App.IndexController = Ember.ArrayController.extend({
itemController: "color",
atIndex: 2,
actions: {
setNewValue: function () {
var index = this.get("atIndex");
alert("How to find collor itemController #" + index + " from here?");
}
}
});
App.ColorController = Ember.ObjectController.extend({
_isPrimary: null,
isPrimary: function (_, newValue) {
if (newValue) {
this.set("_isPrimary", newValue);
}
var value = this.get("_isPrimary");
return value || ["red", "green", "blue"].indexOf(this.get("name")) >= 0;
}.property("name"),
style: function () {
return "color: " + this.get("value") + ";";
}.property("value")
});

<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v2.0.0.js"></script>
<script src="http://builds.emberjs.com/tags/v1.9.1/ember.js"></script>
<script type="text/x-handlebars">
<h2>Welcome to Ember.js</h2>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
<ul>
{{#each item in this}}
<li {{bind-attr style=item.style}}>
{{item.name}}
{{#if item.isPrimary}}
(primary)
{{/if}}
</li>
{{/each}}
</ul>
<hr />
<button type="button" {{action setNewValue}}>Set as primary</button>
<label>at index: {{input value=atIndex}}</label>
</script>
&#13;
如果这个嵌入的东西不起作用,mirror on jsbin。
我尝试的事情:
this.get(1)
this.get("1")
this.get("this.1")
this.get("this.[1]")
this.get("this[1]")
到目前为止没有运气。
如果无法做到这一点,我是否至少可以通过底层模型找到该项目,然后以某种方式使用它来查找其ItemController包装版本?
答案 0 :(得分:4)
要按索引获取项目控制器,您可以使用controllerAt
setNewValue: function () {
var index = this.get("atIndex");
this.controllerAt(index).set("isPrimary", true);
}