L. *_*nna 2 javascript oop backbone.js
我用Backbone创建了一些像以前用Java做的对象.
var Lead = Backbone.Model.extend({
defaults: {
lng: 0,
lat: 0,
distance: 0
},
initialize: function () {
}
});
var Leads = Backbone.Collection.extend({
model: Lead
});
var Map = Backbone.Model.extend({
defaults: {
leads: null
},
initialize: function () {
this.set("leads",new Leads());
},
addJson: function (json) {
var key;
for (key in json) {
if (json.hasOwnProperty(key)) {
var lead = new Lead({ lng: parseFloat(json[key].lng.replace(",", ".")), lat: parseFloat(json[key].lat.replace(",", ".")), distance: json[key].distance });
this.attributes.leads.add(lead);
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,对象Map的属性引导是一个Collection Leads,当它被创建时.但是,这不像Java那样有效,因为我被迫使用:
this.attributes.leads
Run Code Online (Sandbox Code Playgroud)
称之为attribut线索的方法之一.
题:
将对象用作属性是不好的做法,如果是,我该怎么办?
你应该只能this.get('leads').add(lead)
在你的循环中做; this.get('leads)
在这种情况下,将返回(引用)leads
具有该add()
方法的集合.你做不到this.leads.add
因为this.leads
不存在.
Backbone this.attributes
是获取模型的所有属性的便捷方式,但是当调用这些属性时触发事件时this.set()
,this.get()
它们更适合作为接口.
归档时间: |
|
查看次数: |
90 次 |
最近记录: |