I am going through few slides in developing a SPA using Durandal and other JavaScript library.
I have a few questions:
define('projects', [],
function() {
var Projects = function () {
this.myDataLocal = ko.observable();
this.myDataFromServices = null;
};
Projects.prototype.activate = function (activationData) {
this.myDataFromServices = activationData
this.myDataLocal(activationData());
};
Projects.prototype.detached = function () {
this.myDataFromServices(this.myDataLocal());
};
return Projects;
}
);
a. In the above code is
var Projects = function () {
};
a constructor?
b. When we are adding a function to prototype ,
Projects.prototype.activate = function (activationData) {
}
will this also be considered as a constructor and executed automatically on the function load?
c. To qualify a function for a constructor is it enough if we are defining the name of the just like this?
var ProjectsSample100 = function () {
}
A) Not exactly no. Although an object 'Projects' is created.
B) This is not a constructor. This assigns a function to a property on the prototype of the Projects object. In particular in Durandal, when a viewmodel is loaded, Durandal will check for the existance of an 'activate' function on the viewmodel. If none is present, it uses a default function, but in this case we have explicitly set the activation behaviour.
See more about what stages a viewmodel goes through in Durandal here: http://durandaljs.com/documentation/Hooking-Lifecycle-Callbacks.html
C) No. That is just an object getting defined.
A typical constructor looks like this:
function person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myFather = new person("John", "Doe", 50, "blue");
var myMother = new person("Sally", "Rally", 48, "green");
Notice the use of 'this' to assign to 'fields' on the object, and the use of 'new' to create new instances with this constructor.
I have stolen this example from here: http://www.w3schools.com/js/js_object_definition.asp