如何将视图'id设置为模型'id
how to set my view's id to be my model's id?
我是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;
}
相关文章:
- 尝试JSON.stringify Ember模型时Id丢失
- 从模型传递id以查看Backbone.js
- Strongloop环回:根据相关模型的id进行过滤
- Ember.js为特定的模型id添加css类
- 如何在创建保存新模型时获取id
- 主干模型通过ID获取JSON元素
- Ember模型create()没有创建ID,适配器必须实现“;createRecord”;
- 在不同的模型中获取模型id会在主干中创建表单
- 角度 - 动态 ng 模型名称,ID 在 ng 重复中
- 角度超前,其中模型作为 Id 和文本作为数组对象的名称
- 使用主干获取集合.js但未设置每个模型的 id
- 要求不传递主干模型 ID
- backbonejs 获取 id 列表的模型
- 我应该如何从 json 的所有级别(模型、数组)中删除“id”键
- 主干模型销毁未传递模型 ID 的 url
- 通过 id-Extjs 将数据加载到模型中
- 如何阻止单个模型将其 id 添加到 Backbone 中的 url
- 在 Angular JS 中从模型检索到控制器的 id
- 将 Model.ID 绑定到复选框列表,并将模型.X、模型.Y 等属性发布到控制器
- 如何从集合中提取特定的模型,并设置id模型