I am using Knockout.js for a rich client application and it will consist of large number of knockout.js ViewModels. In the development, I noticed two ways of creating knockout.js ViewModels.
First way.
function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");}
Second way.
var appViewModel = {
this.firstName = ko.observable("Bert"),
this.lastName = ko.observable("Bertington")};
Is there any specific difference in these two methods of declaring ViewModels?
In knockout.js official page examples they have used the first way. But in third party frameworks like Knockout-validations.js has used second way. Which way should I use? Any specific advantage in using it?
I found out if I use first way, then I cant use Knockout-validations.js framework. I am really confused on this matter. Any comment is appreciated.
Thank you.
The first way defines an object constructor but does not instantiate a new object, you can pass in arguments this way. If you’re creating multiple objects/models this would definitely be less clunky than the second way.
The second way is using object initializer syntax, this instantiates a new object in memory with whatever fields you set it to. In general this produces for smaller code size; if you’re creating two objects of the same or similar structures, use the first way.
There is no reason why you can’t use the first in place of the second. Simply creating a new object and pass it in wherever it is needed.
This:
creates the same object as this:
The first one just allows for more
AppViewModels to be created, e.g.new AppViewModel("Joe", "Shmoe")