Skip to content

Instantly share code, notes, and snippets.

@zeckdude
Last active December 3, 2015 06:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeckdude/8baf5c482dd71623bdc1 to your computer and use it in GitHub Desktop.
Save zeckdude/8baf5c482dd71623bdc1 to your computer and use it in GitHub Desktop.
Backbone from Scratch Chapter Project: Models
// BACKBONE MODELS PROJECT
console.log("Begin - BACKBONE MODELS PROJECT");
// Create a Backbone model for a Vehicle.
// A Vehicle is uniquely identified via one of its attributes called “registrationNumber”, which cannot be null or undefined.
// Vehicles can be retrieved from the server at “/api/vehicles”.
// A Vehicle should have a method called start(), which logs a message in the console: “Vehicle started.”
var Vehicle = Backbone.Model.extend({
idAttribute: "registrationNumber",
urlRoot: "/api/vehicles",
validate: function(attrs) {
if (typeof attrs.registrationNumber === "undefined" || attrs.registrationNumber === null) {
return "Registration Number may not be null or undefined";
}
},
start: function() {
console.log("Vehicle Started");
}
});
// Derive a Backbone model from the Vehicle and call it Car.
// Override the start() method of the Vehicle inside the Car and log a message as: “Car with registration number {registrationNumber} started.”, where {registrationNumber} should be the value of the registrationNumber attribute.
var Car = Vehicle.extend({
start: function() {
console.log("Car with registration number " + this.attributes.registrationNumber + " started.")
}
});
// Create an instance of the Car and initialise it with the following attributes:
// • registrationNumber: XLI887
// • color: Blue
var blueRide = new Car({
registrationNumber: "XLI887",
color: "Blue"
});
// Remove the registrationNumber attribute of the car object.
blueRide.unset("registrationNumber");
// Ask the car if it’s valid, and if not, log the validation error in the console.
if(!blueRide.isValid()) {
console.log(blueRide.validationError);
}
// Set the registrationNumber to XLI887 again.
blueRide.set("registrationNumber", "XLI887");
// Ask the car if it’s valid and log the result in the console.
console.log(blueRide.isValid());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment