如何在Ember中以编程方式执行ArrayController[index]

How to programmatically perform ArrayController[index] in Ember?

本文关键字:ArrayController 执行 index 方式 编程 Ember      更新时间:2023-09-26

我知道如何通过特定属性(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>

如果这个嵌入的东西不起作用,请在jsbin上镜像。

我尝试过的东西:

  • this.get(1)
  • this.get("1")
  • this.get("this.1")
  • this.get("this.[1]")
  • this.get("this[1]")

到目前为止运气不好。

如果不能做到这一点,我至少可以通过底层模型找到项目,然后以某种方式使用它来找到它的ItemController包装版本吗?

要通过索引获得物品控制器,可以使用controllerAt

setNewValue: function () {
  var index = this.get("atIndex");
  this.controllerAt(index).set("isPrimary", true);
}

更新的jsbinhttp://emberjs.jsbin.com/yajipogive/1/edit