3

我有一个具有tooltip属性的视图。我想在initializeor上动态设置该属性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在当前视图上动态设置我的(工具提示),为什么它会影响下一个视图?

谢谢

4

2 回答 2

7

您可以将attribute属性定义为返回对象作为结果的函数。因此,您可以动态设置属性。

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

我希望它有帮助。

于 2013-03-27T13:28:17.730 回答
5

我认为你的问题就在这里:

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

.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();
};

_ensureElement调用是使用的东西,你attributes会注意到它在initialize被调用之前出现。该顺序与原型行为相结合是您的属性出现在视图的下一个实例上的原因。这attributes实际上适用于静态属性,您的this.$el.attr('tooltip', ...)解决方案是处理动态属性的好方法。

于 2012-06-28T02:34:02.493 回答