Ember:从ArrayController动作更新ObjectController属性?

时间:2015-05-08 20:10:17

标签: ember.js

免责声明:我对Ember很新。对任何人可能有的建议都很开放。

我在ArrayController中有一个应该设置ObjectController属性的动作。在创建新对象时如何访问正确的上下文来设置该属性?

这是缩略的应用代码,显示了我最近的尝试:

ChatApp.ConversationsController = Ember.ArrayController.extend({
  itemController: 'conversation',
  actions: {
    openChat: function(user_id, profile_id){
      if(this.existingChat(profile_id)){
        new_chat = this.findBy('profile_id', profile_id).get('firstObject');
      }else{
        new_chat = this.store.createRecord('conversation', {
          profile_id: profile_id,
        });
        new_chat.save();
      }
      var flashTargets = this.filterBy('profile_id', profile_id);
      flashTargets.setEach('isFlashed', true);
    }
  },
  existingChat: function(profile_id){
    return this.filterBy('profile_id', profile_id).get('length') > 0;
  }
});

ChatApp.ConversationController =  Ember.ObjectController.extend({
  isFlashed: false
});

相关模板代码:

{{#each conversation in controller itemController="conversation"}}
  <li {{bind-attr class="conversation.isFlashed:flashed "}}>
    <h3>Profile: {{conversation.profile}} Conversation: {{conversation.id}}</h3>
    other stuff
  </li>
{{/each}}

2 个答案:

答案 0 :(得分:1)

ArrayControllerItemController are going to be depreciated。当你是Ember的新手时,我认为你最好不要使用它们并专注于应用即将发生的变化。

我可以建议您创建某种代理对象来处理您的其他属性(isFlashed,但也像isCheckedisActive等)。这个代理对象(实际上是一个代理对象数组)看起来像这样(并且是一个计算属性):

proxiedCollection: Ember.computed.map("yourModelArray", function(item) {
  return Object.create({
    content: item,
    isFlashed: false
  });
});

现在,您的模板可能如下所示:

{{#each conversation in yourModelArray}}
  <li {{bind-attr class="conversation.isFlashed:flashed "}}>
    <h3>Profile: {{conversation.content.profile}} Conversation: {{conversation.content.id}}</h3>
    other stuff
  </li>
{{/each}}

最后,但并非最不重要的是,你摆脱了ArrayController。但是,您不会使用filterBy方法(因为它只允许一级深度,并且您将拥有代理对象数组,每个代理对象都会处理您过滤的某些属性 - 例如id)。您仍然可以使用显式forEach并提供处理设置的函数:

this.get("proxiedCollection").forEach((function(_this) {
  return function(proxiedItem) {
    if (proxiedItem.get("content.profile_id") === profile_id) {
      return proxiedItem.set("isFlashed", true);
    }
  };
})(this));

答案 1 :(得分:1)

我不明白为什么你需要一个处理为列表中所有元素设置属性的对象。让每个项目自行处理,这意味着components时间。

无论如何,

ControllersViews都会被弃用,所以你会这样做:

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return [...];
  }
});

App.ConversationComponent = Ember.Component.extend({
  isFlashed: false,
  actions: {
    // handle my own events and properties
  }
});

并在您的模板中

{{#each item in model}}
  {{conversation content=item}}
{{/each}}

因此,每当您向模型添加项目时,都会创建一个新组件,您无需执行existingChat逻辑。

相关问题