2012-06-27 37 views
3

我有一個tooltip屬性的視圖。我想在initializerender上動態設置該屬性。然而,當我將它,它出現在該視圖,而不是當前的下一個實例:骨幹視圖下一個實例化的屬性集?

var WorkoutSectionSlide = Parse.View.extend({  
     tag : 'div', 
     className : 'sectionPreview', 
     attributes : {}, 

     template : _.template(workoutSectionPreviewElement), 

     initialize : function() { 
//   this.setDetailsTooltip(); // doesn't work if run here either 
     }, 

     setDetailsTooltip : function() { 
      // build details 
      ... 

      // set tooltip 
      this.attributes['tooltip'] = details.join(', '); 
     }, 

     render: function() {    
      this.setDetailsTooltip(); // applies to next WorkoutViewSlide 

      // build firstExercises images 
      var firstExercisesHTML = ''; 
      for(key in this.model.workoutExerciseList.models) { 
       // stop after 3 
       if(key == 3) 
        break; 
       else 
        firstExercisesHTML += '<img src="' + 
         (this.model.workoutExerciseList.models[key].get("finalThumbnail") ? 
           this.model.workoutExerciseList.models[key].get("finalThumbnail").url : Exercise.SRC_NOIMAGE) + '" />'; 
      } 

      // render the section slide 
      $(this.el).html(this.template({ 
       workoutSection : this.model, 
       firstExercisesHTML : firstExercisesHTML, 
       WorkoutSection : WorkoutSection, 
       Exercise : Exercise 
      })); 


      return this; 
     } 
    }); 

這裏是我初始化視圖:

// section preview 
$('#sectionPreviews').append(
    (new WorkoutSectionPreview({ 
     model: that.workoutSections[that._renderWorkoutSectionIndex] 
    })).render().el 
); 

如何動態設置我attribute(tooltip)就當前視圖而言,爲什麼它會影響下一個視圖?

感謝

回答

5

我認爲你的問題就在這裏:你把在.extend({...})

var WorkoutSectionSlide = Parse.View.extend({  
    tag : 'div', 
    className : 'sectionPreview', 
    attributes : {} // <----------------- This doesn't do what you think it does 

一切都在WorkoutSectionSlide.prototype結束了,他們沒有複製到的情況下,他們通過共享通過原型的所有實例。在你的情況下的結果是,你有一個attributes對象,由所有WorkoutSectionSlide s共享。

此外,視圖的attributes僅用於而對象是being constructed

var View = Backbone.View = function(options) { 
    this.cid = _.uniqueId('view'); 
    this._configure(options || {}); 
    this._ensureElement(); 
    this.initialize.apply(this, arguments); 
    this.delegateEvents(); 
}; 

_ensureElement呼叫是使用attributes的事情,你會發現,它涉及initialize被調用之前。該命令與原型行爲相結合,就是爲什麼你的屬性顯示在下一個視圖的實例上。 attributes實際上是用於靜態屬性,您的this.$el.attr('tooltip', ...)解決方案是處理動態屬性的好方法。

+0

這很有道理。不過,我已經更新了我'initialize'到正是和我沒有得到期望的結果:( – Garrett

+0

@Garrett:?什麼是閱讀'attributes'我沒有看到任何訪問它在你的代碼 –

+1

我固定它'這一點。$ el.attr(「提示」,...)',但想知道是否有更好的解決方案。感謝您的見解,我很欣賞你無盡的奉獻SO(和我大部分的問題)。 我使用'attributes'對'el'所以我最終的結果是''

...
Garrett

7

您可以將attribute屬性定義爲返回對象作爲結果的函數。所以你可以動態設置你的屬性。

var MyView = Backbone.View.extend({ 
    model: MyModel, 
    tagName: 'article', 
    className: 'someClass', 
    attributes: function(){ 
     return { 
      id: 'model-'+this.model.id, 
      someAttr: Math.random() 
     } 
    } 
}) 

我希望得到它。

+0

非常有幫助謝謝! – trs79