2014-01-15 57 views
2

我有一個典型的集合持有模型的結構。骨幹 - 訪問集合的其他意見

在視圖中,每個對象都有一個'編輯'按鈕,它應該可以禁用其他對象的所有'編輯'按鈕。

我想知道做這件事的最佳做法是什麼。謝謝!!

回答

1

好了,我想出了以下方法:

假設模型有一個屬性status,當它被修改爲active我想隱藏在其他條目的編輯按鈕(或只需禁用它)。

我收藏視圖監聽模型中的變化:

initialize: function(){ 
    this.listenTo(this.collection, "change:status", this.triggerEditable); 
}, 

的偵聽器回調看起來像這樣:

triggerEditable: function(obj){ 
    var triggerValue = null; 

    // I am interested in a status which became 'active' or stopped being 'active' 
    if (obj.get("status") == 'active' && obj.previous("status") != 'active') { 
     triggerValue = "editable:false"; 
    } else if (obj.get("status") != 'active' && obj.previous("status") == 'active') { 
     triggerValue = "editable:true"; 
    } 

    // for any other status change - return 
    if (!triggerValue) return; 

    // trigger is fired for all other objects in the collection 
    _.each(obj.collection.without(obj),function(otherObj) { 
     otherObj.trigger(triggerValue); 
    }); 
} 

所以,當一個對象被激活或停止活躍,edidable:falseedidable:true是爲所有其他條目觸發的。所有我需要做的是添加到模型視圖初始化監聽器:

this.listenTo(this.model, "editable:false", this.disableEdit); 
this.listenTo(this.model, "editable:true", this.enableEdit); 

在這裏,我想我可以兩行合併爲一個,先聽editable命名空間(如何?)和然後通過傳遞一個參數給函數(又是如何?)。

從這裏是直線前進 - 實現偵聽器回調:

disableEdit: function() { 
    var e = this.$el.find('button.edit') 
    e.attr('disabled','disabled'); 
} 

如果有人有什麼要補充的,或者使這種解決方案更好,我會很高興地聽到。 無論如何,希望它會對別人有幫助!

2

您可以在默認設置爲true的模型上添加屬性editable。然後當您點擊其中一個視圖上的「編輯」按鈕時,您可以遍歷其他視圖的所有模型,並將editable設置爲false。在視圖上,您​​將聽取模型更改並重新渲染視圖。如果editablefalse,您可以禁用編輯按鈕。

+0

不錯的一個!是否可以添加到數據庫中不存在的模型屬性?怎麼樣? – guyaloni

+0

說實話,我從來沒有將我的骨幹模型同步到服務器。我無法對客戶端模型進行映像,因此不允許擁有自己的屬性。你可以有一個自定義的[sync](http://backbonejs.org/#Model-sync)方法實現,但這可能不是最漂亮的解決方案。 – rednaw

+0

也許:http://stackoverflow.com/questions/11941010/client-side-only-attributes-in-backbone – rednaw