View model of a Knockout.js ad. There are two methods.

I use Knockout.js for a rich client application, and it will consist of a lot of newbies. ViewModels. In development, I noticed two ways to create knockout.js ViewModels. The first way.

function AppViewModel() {
this.firstName = ko.observable("Bert");
this.lastName = ko.observable("Bertington");}

The 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 the official examples of the knockout.js page, they used the first method. But in third-party structures, such as Knockout-validations.js , the second method is used. How should I use? Any specific advantage to use?

I found out if I am using the first method, but I cannot use the Knockout-validations.js structure. I am really confused about this issue. Any comments are welcome.

Thank.

+5
source share
2 answers

The first method defines the constructor of the object, but does not instantiate a new object, you can pass arguments in this way. If you create multiple objects / models, this will definitely be less cumbersome than the second method.

The second way is to use the object initializer syntax, which creates a new object in memory with any fields in which you set it. In general, this results in a smaller code size; if you create two objects of the same or similar structures, use the first method.

, . , .

:

function AppViewModel(fName, lName) {
    var self = this;
    self.firstName = ko.observable(fName);
    self.lastName = ko.observable(lName);
}
...
var appViewModel = new AppViewModel("Bert", "Bertington");

, :

var appViewModel = {
    this.firstName = ko.observable("Bert"),
    this.lastName = ko.observable("Bertington")
};

AppViewModel, . new AppViewModel("Joe", "Shmoe")

+3

, , , , JavaScript. , JavaScript, :

, JavaScript , . , . , , Knockout-Validation . , Knockout-Validation. , .

+2

All Articles