I am new to the world of Javascript frameworks and I really like the way Backbonejs works.
But I have one question regarding the constructors of Models and Views. I have developed for years using Java like languages, and I am used to define constructors like this:
public Car(Manufacturer manufacturer, String model, Color color) {
this.manufacturer = manufacturer;
this.model = model;
this.color = color;
}
But I see in the documentation and in other tutorials that people usually don’t declare a specific constructor when defining a Model or View, and they just construct objects like this:
var car = new Car({manufacturer: ford, model: "Mustang", color: "red"});
Is it wrong or “ugly” to define a constructor like:
window.Car = Backbone.Model.extend({
initialize: function(manufacturer, model, color) {
this.manufacturer = manufacturer;
this.model = model;
this.color = color;
}
});
If so, can you explain why ?
I really hope this is not a stupid question, I have not found any related questions.
Your idea of passing in multiple arguments rather than an object is fine, however you would want the initialize function to look like this:
You need to use
setto access the attributes object. By usingthisyou are attaching the attributes directly to the model.The reason that backbone uses the attributes object is so that it can automaticaally trigger events when you change attributes. It is also a way to encapsulate your fields in methods, in the same way you would create
private Manufacturer manufacturer;and
public Manufacturer getManufacturer()in java.