簡體   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