I have a backbone model like so
define([
'underscore',
'backbone'
],function( _,Backbone) {
var Task = Backbone.Model.extend({
//api url
url:'',
methodToURL: {
'read': './api/tasks/index',
'create': './api/tasks/task',
'update': './api/tasks/task',
'delete': './api/tasks/task'
},
sync: function(method, model, options) {
options = options || {};
options.url = this.methodToURL[method.toLowerCase()];
Backbone.sync(method, model, options);
}
});
return Task;
});
And a collection
define(['underscore','backbone','models/task'],function( _,Backbone,Task) {
var TaskCollection = Backbone.Collection.extend({
//Model
model:Task,
//api url
url:'',
methodToURL: {
'read': './api/tasks/index',
'create': './api/tasks/task',
'update': './api/tasks/task',
'delete': './api/tasks/task'
},
sync: function(method, model, options) {
options = options || {};
options.url = this.methodToURL[method.toLowerCase()];
Backbone.sync(method, model, options);
},
//construct
initialize: function() {
this.sort_key = 'end';
this._model = new Task();
this.fetch();
},
comparator: function(a,b) {
a = a.get(this.sort_key);
b = b.get(this.sort_key);
return a > b ? 1
: a < b ? -1
: 0;
},
mark_complete: function(task_id) {
var task_status = 0;
console.log(this.model);
this.model.save({id:task_id,task_status:task_status});
},
mark_incomplete: function(task_id) {
var task_status = 1;
console.log(this.model);
this.model.save({id:task_id,task_status:task_status});
},
sort_by_status: function() {
this.sort_key = 'task_status';
this.sort();
},
sort_by_task_tag: function() {
this.sort_key = 'task_group';
this.sort();
}
});
return TaskCollection;
});
When i the mark_complete method runs the model is logged to the console, but it logs this
“function (){ parent.apply(this, arguments); } ” and says “function (){ parent.apply(this, arguments); } has no method 'save'“;
Am guessing the model is supposed to be instantiated so the collection can have access it to its methods, so what is wrong?
The
modelproperty is just a constructor thatCollectionuses when you add a model to the collection. It is intended to make your life easier when you try to input data to the collection. Instead of always calling the constructor when adding aTaskmodel toTaskCollection, you’d just input a JavaScript object and it will do the same thing.So this is how your code would look like when you would want to insert a model without setting the
modelproperty to yourTaskCollectionAnd this is how your code would look like if you had set the
modelpropertyAs you can see, you don’t need to call the
Taskconstructor; the instance ofTaskCollectionwill call it for you.And this is why instances of
TaskCollectionwill only have themodelproperty set to the actual constructor ofTask, not an initialized version.