0

我有一個包含顯示選項列表的子視圖的父視圖(用於汽車引擎)。其中一個選項是將新集合添加到父視圖。從子視圖向父視圖添加新集合

我的子視圖初始化函數如下:

initialize: function (engine) { 
    this.engine = engine; //parent object 
    this.valves = engine.valves; //may or may not be empty 
}; 

然後,我有這種方法,增加了集合(閥)時,按下按鈕:所以,現在,我創建

addPerformanceValves: function() { 
    var self = this; 
    if (this.valves.lentgh == 0) { 
     this.valves = new ValveCollection(); 
     this.valves.url = function() { 
      return '/api/engines/auto/performance/parts/' + self.id + '/valves'; 
     } 
    } 
    this.$('.performanceParts').show(); 
} 

新的集合,我如何將它添加到父項?

回答

1

有多種方法可以實現這一點。

傳遞父對象沿層次

就像你已經在做,你可以從父對象調用一個函數來傳遞新的集合。

var Child = Backbone.View.extend({ 
    initialize: function(options) { 
     options = options || {}; 
     this.engine = options.engine; //parent object 
     this.valves = engine.valves; //may or may not be empty 
    }, 
    addPerformanceValves: function() { 
     var self = this; 
     if (this.valves.lentgh == 0) { 
      this.valves = new ValveCollection(); 
      this.valves.url = function() { 
       return '/api/engines/auto/performance/parts/' + self.id + '/valves'; 
      } 

      // call the parent 
      this.engine.addNewCollection(this.valves); 
     } 
     this.$('.performanceParts').show(); 
    } 
}); 

var Parent = Backbone.View.extend({ 
    addNewCollection: function(collection) { 
     // do what you want with the collection 
     this.newCollection = collection; 
    } 
}); 

觸發事件

的一種方式,以避免強耦合是觸發從子視圖的事件,對此家長在聽。

var Child = Backbone.View.extend({ 
    initialize: function(options) { 
     options = options || {}; 
     this.valves = options.valves; //may or may not be empty 
    }, 
    addPerformanceValves: function() { 
     var self = this; 
     if (this.valves.lentgh == 0) { 
      this.valves = new ValveCollection(); 
      this.valves.url = function() { 
       return '/api/engines/auto/performance/parts/' + self.id + '/valves'; 
      } 

      // call the parent 
      this.trigger('child:collection', this.valves); 
     } 
     this.$('.performanceParts').show(); 
    } 
}); 

var Parent = Backbone.View.extend({ 
    initialize: function() { 
     this.child = new Child({ valves: this.valves }); 

     // listen to child view events 
     this.listenTo(this.child, 'child:collection', this.addNewCollection); 
    }, 
    addNewCollection: function(collection) { 
     // do what you want with the collection 
     this.newCollection = collection; 
    } 
}); 

然後,子視圖只有它所需要的東西,僅此而已。它有助於將責任保留在正確的地方。

相關問題