我有一个具有tooltip
属性的视图。我想在initialize
或render
上动态设置该属性。但是,当我设置它时,它出现在该视图的下一个实例而不是当前实例上:
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
(工具提示),为什么它会影响下一个视图?
谢谢
您可以将attribute
属性定义为返回对象作为结果的函数。因此,您可以动态设置属性。
var MyView = Backbone.View.extend({
model: MyModel,
tagName: 'article',
className: 'someClass',
attributes: function(){
return {
id: 'model-'+this.model.id,
someAttr: Math.random()
}
}
})
我希望它能成功。
你的问题就在这里:
var WorkoutSectionSlide = Parse.View.extend( {
tag : 'div',
className : 'sectionPreview',
attributes : {} // <----------------- This doesn't do what you think it does
您放入.extend({...})
中的所有内容最终都会WorkoutSectionSlide.prototype
,它们不会复制到实例中,而是通过原型由所有实例共享。在您的情况下,结果是你有一个由所有WorkoutSectionSlide
共享的attributes
对象。
此外,视图的attributes
仅在构造对象时使用:
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', ...)
解决方案是处理动态属性的好方法。