I have a backbone collection and I want to create a method that populates the collection. What I found is the push method but this require to iterate over all the items:
define([
...
], function($, _, Backbone, imagesCollection, imageTemplate, gridView) {
var AppView = Backbone.View.extend({
el: '#container',
template: _.template( imageTemplate ),
events: {
'click #search': 'search'
},
initialize: function() {
this.input = this.$('#search-term');
},
populate: function(data) {
for (var i=0;i<data.length;i++) {
imagesCollection.push(data[i]);
}
//IS THERE ANY WAY TO PREVENT ITERATING OVER ALL THE ITEMS?
},
search: function() {
$.ajax({
type: 'get',
url: myurl,
dataType:'jsonp',
success: function(response){
populate(response);
}
});
}
});
return AppView;
});
Is there any other solution?
I am new to backbone so if you see anything wrong – please tell me.
There are at least two ways to populate a backbone collection without iterating in my own code.
method add (which appends models you passed in)
method reset (which replaces all models in the collection by the new ones you provide)
See http://backbonejs.org/#Collection-reset and http://backbonejs.org/#Collection-add