0
我與Backbone.js的一個beggineer,我想我的渲染el
是如何將我的視圖的id設置爲我的模型ID?
<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')
試圖訪問一個沒有b的模型een加載到視圖呢。 (this.model
是undefined
)
我該如何將我的視圖ID設置爲我的模型ID?
+謝謝你的回答,也是你的時間。
你試過設置視圖的初始化方法裏面的價值?沒有看源頭,似乎模型還沒有被設置的時候,它正在試圖設置建設的ID – kinakuta
我現在更新的職位,並把完整的代碼,我以爲我做了一件好事,只是把問題 – asedsami
你應該可以用'id:function(){return this.model.get('item_id')}'來代替。我必須跑步,否則我會給你一個真實的答案。 –