Gar*_*ett 3 javascript backbone.js backbone-views
我有一个具有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;
}
});
Run Code Online (Sandbox Code Playgroud)
以下是我初始化视图的方法:
// section preview
$('#sectionPreviews').append(
(new WorkoutSectionPreview({
model: that.workoutSections[that._renderWorkoutSectionIndex]
})).render().el
);
Run Code Online (Sandbox Code Playgroud)
如何attribute在当前视图上动态设置我的(工具提示),为什么它会影响下一个视图?
谢谢
您可以将attribute属性定义为将对象作为结果返回的函数.因此,您可以动态设置属性.
var MyView = Backbone.View.extend({
model: MyModel,
tagName: 'article',
className: 'someClass',
attributes: function(){
return {
id: 'model-'+this.model.id,
someAttr: Math.random()
}
}
})
Run Code Online (Sandbox Code Playgroud)
我希望它能解决.
我认为你的问题就在这里:
var WorkoutSectionSlide = Parse.View.extend( {
tag : 'div',
className : 'sectionPreview',
attributes : {} // <----------------- This doesn't do what you think it does
Run Code Online (Sandbox Code Playgroud)
那你把一切都.extend({...})结束了在WorkoutSectionSlide.prototype,他们没有复制到的情况下,他们通过原型所有实例共享.在您的情况下,结果是您有一个attributes由所有WorkoutSectionSlides 共享的对象.
此外,视图attributes仅在构造对象时使用:
var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
this._configure(options || {});
this._ensureElement();
this.initialize.apply(this, arguments);
this.delegateEvents();
};
Run Code Online (Sandbox Code Playgroud)
该_ensureElement呼叫是使用的东西attributes,你会发现它到来之前initialize被调用.该顺序与原型行为相结合,是您的属性显示在视图的下一个实例上的原因.该attributes真的意味着静态属性,你的this.$el.attr('tooltip', ...)解决方案来处理动态属性的好方法.