如何将我的观点ID设为我的模特ID?

时间:2015-09-08 23:04:23

标签: javascript backbone.js backbone-views

我是BackBone.js的beggineer,我希望我的渲染el

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

现在使用.rectangle属性设置课程className非常简单,问题是设置视图的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.modelundefined

如何将我的观点ID设为我的模特身份?

+感谢您的回答以及您的时间。

0 个答案:

没有答案