2012-06-27 38 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