繁体   English   中英

灰烬:从ArrayController操作更新ObjectController属性?

[英]Ember: Update ObjectController property from ArrayController action?

免责声明:我是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}}

ArrayControllerItemController 将被折旧 当您刚接触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));

我不明白为什么需要一个对象来处理列表中所有元素的设置属性。 让每个项目自己照顾自己,这意味着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 Chat逻辑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM