如何将视图'id设置为模型'id

how to set my view's id to be my model's id?

本文关键字:id 模型 设置 视图      更新时间:2023-09-26

我是BackBone.js的初学者,我希望我的渲染el

<div class="rectangle" id="ITEM_ID_OF_MY_MODEL"</div>

现在使用className属性设置类.rectangle很容易,问题是设置视图的id

var Rectangle = Backbone.Model.extend({
    defaults: {
        item_id: this.cid
    }
});
var RectangleView = Backbone.View.extend({
    tagName: 'div',
    className: 'rectangle',
    initiliaze: function() {
        this.id = this.model.get('item_id');
    },
    events: {
        'click': 'move'
    },
    render: function(){
        console.log(this.model.cid); // prints c1 then c2 then c3
        this.setDimensions();
        this.setPosition();
        this.setColor();
        return this;
    },
    setPosition: function() {
        var position = this.model.get('position');
        this.$el.css({
            left: position.x,
            top: position.y
        });
    },
    setDimensions: function() {
        this.$el.css({
            width: this.model.get('width') + 'px',
            height: this.model.get('height') + 'px'
        });
    },
    setColor: function() {
        this.$el.css('background-color', this.model.get('color'));
    },
    move: function() {
        this.$el.css('left', this.$el.position().left + 10);
    }
});
var props1 = {
    width: 100,
    height: 60,
    position: {
        x: 300,
        y: 150
    },
    color: 'tomato',
    item_id: 1
}
var props2 = {
    width: 200,
    height: 20,
    position: {
        x: 100,
        y: 100
    },
    color: 'grey',
    item_id: 2
}
var props3 = {
    width: 140,
    height: 160,
    position: {
        x: 200,
        y: 300
    },
    color: 'blue',
    item_id: 3
}
var models = [
    new Rectangle(props1),
    new Rectangle(props2),
    new Rectangle(props3)
];
_(models).each(function(model) {
    var myView = new RectangleView({model: model});
    var myRenderedElement = myView.render().el;
    $('#canvas').append(myRenderedElement)
});

错误是:

Uncaught TypeError: Cannot read property 'get' of undefined

,如果我这样做:

id: this.model.cid

我得到一个类似的错误:

Uncaught TypeError: Cannot read property 'cid' of undefined

所以this.model.get('item_id')正在尝试访问尚未加载到视图的模型。(this.model is undefined)

我怎么能设置我的视图的id是我的模型的id?

您可以在渲染函数中更改视图的id或类。记住这个。El引用view元素。因此,我们可以改变元素的任何属性。

render: function()
{
    this.el.id = this.model.cid; // this line here
    var template = this.template(this.model.toJSON());
    this.$el.html(template);
    return this; 
}