Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defining a new backbone collection

I was trying to extend backbone collections, the first way i was doing new in the declaration and in the second I declared first and then I created a new instance. Is doing the first wrong, what is the difference?

var AppointmentList = new Backbone.Collection.extend({
  model: Appointment
});

and

var AppointmentList = Backbone.Collection.extend({
  model: Appointment
});

var aptlist = new AppointmentList();
like image 361
whatf Avatar asked Feb 10 '13 09:02

whatf


People also ask

What is a Backbone project?

The Backbone Project is a large-scale integrated transportation infrastructure program (port, dry port, airport, rail and highway) initiated, designed and developed by Petrolin Group. It is composed of five components critical to the development of countries in West Africa, notably Benin, Niger and Nigeria.

What are collections in Backbone JS?

A Backbone. js Collections are a group of related models. It is useful when the model is loading to the server or saving to the server. Collections also provide a helper function for performing computation against a list of models.

How do I set up backbone JS?

Downloading the UI library from its official website Development Version − Right click on this button and save as and you get the full source JavaScript library. Production Version − Right click on this button and save as and you get the Backbone-min. js library file which is packed and gzipped.


1 Answers

The first one will break

var Appointment = Backbone.Model.extend({
    defaults: {
        "time": "0000",
        "note": "This is an appointment"
    }
});


var AppointmentList = new Backbone.Collection.extend({

    model: Appointment

});

var aptlist = new AppointmentList();

In in Backbone.js we have

  var extend = function(protoProps, staticProps) {

    var parent = this;
    var child;


    if (protoProps && _.has(protoProps, 'constructor')) {
      child = protoProps.constructor;
    } else {
      child = function(){ return parent.apply(this, arguments); };
    }

    _.extend(child, parent, staticProps);


    var Surrogate = function(){ this.constructor = child; };

    Surrogate.prototype = parent.prototype;

    child.prototype = new Surrogate;


    if (protoProps) _.extend(child.prototype, protoProps);


    child.__super__ = parent.prototype;

    return child;

  };

If you instantiate Backbone.Collection.extend with the new operator, then the var parent = this will refer to the extend object, but if you don't use new then var parent = this will refer to Backbone.Collection and since you can only call .apply on functions, the code will break here:

child = function(){ return parent.apply(this, arguments); };

parent will be an object. Backbone.Collection is a function

like image 150
richie Avatar answered Sep 24 '22 08:09

richie