我在主干中有一个应用程序,在主应用程序中我有一个事件点击onan元素,当我点击它我想要在其中添加其集合模型的另一个应用程序...是一个集合的集合。 我正在使用需要我检索的错误是:
Uncaught TypeError: Object [object Object] has no method 'addElement'
这是我的主要应用: 型号:
define(['backbone', 'collections/element'],function(Backbone, ElementCollection){
var DesignModel = Backbone.Model.extend({
initialize:function(){
console.log('Initialized Design model');
_.defaults(this, {
elements: new ElementCollection()
});
},
addElement: function(elements, options) {
return this.elements.add(elements, options);
}
});
return DesignModel;
});
收集:
define(['backbone', 'models/design'], function(Backbone, DesignModel){
var designCollection = Backbone.Collection.extend({
model: DesignModel
});
return designCollection;
});
查看:
define(['jquery' , 'backbone', 'models/design', 'collections/design', 'views/element'],
function($, Backbone, DesignModel, DesignCollection, ElementView){
var DesignView = Backbone.View.extend({
el:$('#page'),
initialize: function(){
console.log('initialize DesignView');
this.collection = new DesignCollection();
var here = this;
$('#insert-dynamic-element').click(function(){
var element = new ElementView();
here.collection.addElement(element);
});
},
render: function(){
}
})
return DesignView;
});
应用程序插入主内部: 型号:
define(['backbone'],function(Backbone){
var ElementModel = Backbone.Model.extend({
defaults:{
name:'Design',
type:'img'
},
initialize:function(){
console.log('Initialized Element model');
}
});
return ElementModel;
});
收集:
define(['backbone', 'models/element'], function(Backbone, ElementModel){
var elementCollection = Backbone.Collection.extend({
model: ElementModel
});
return elementCollection;
});
查看
define(['jquery' , 'backbone', 'models/element', 'collections/element'],
function($, Backbone, ElementModel, ElementCollection){
var ElementView = Backbone.View.extend({
el:$('#page'),
initialize: function(){
console.log('initialize ElementView');
this.collection = new ElementCollection();
},
render: function(){
}
})
return ElementView;
});
我该如何解决这个问题?
错误是在主应用程序中我单击元素并尝试进行addElement
答案 0 :(得分:1)
此方法在DesignModel
而非DesignCollection
因此,当您调用此方法时,它会在Collection
内搜索不存在的导致错误的方法。
另外,为什么要使用jQuery绑定事件时,可以选择使用Native Backbone events
要解决此问题,请将方法添加到集合
define(['backbone', 'models/design'], function(Backbone, DesignModel){
var designCollection = Backbone.Collection.extend({
model: DesignModel,
addElement: function(element, options) {
return this.add(element, options);
}
});
return designCollection;
});