Reputation: 58662
While going through the examples of KnockoutJS, I saw the below code.
function WebmailViewModel() {
// Data
var self = this;
self.folders = ['Inbox', 'Archive', 'Sent', 'Spam'];
self.chosenFolderId = ko.observable();
// Behaviours
self.goToFolder = function(folder) { self.chosenFolderId(folder); };
};
ko.applyBindings(new WebmailViewModel());
I am not an expert in Javascript, but bit confused by the usage self.chosenFolderId(folder);
chosenFolderId is a property, and assigned ko.observable();
From the experience with other languages,
self.chosenFolderId(folder);
If you can just point to an article which explains this that will do.
Thanks.
Upvotes: 0
Views: 110
Reputation: 140210
In javascript functions can be assigned to variables, passed to functions as arguments, returned from functions and so on. In other words, the'yre First-class.
Upvotes: 0
Reputation: 160170
chosenFolderId
is a property, but properties may be functions (and must be, in this case).
So ko.observable
returns a function that takes a single argument (the folder).
It's no different than the next line:
self.goToFolder = function(folder) { ... };
where the goToFolder
property is being set to a function.
folder
itself is "defined" as a parameter as goToFolder
's parameter. Whatever calls goToFolder
provides a value for folder
.
Upvotes: 1
Reputation: 20209
Functions in javascript are first-class objects. ko.observable()
is a function call, and its return value is itself a function.
Basically I can do something like this:
var observable = function(some_param) {
return function(some_other_param) {
// do something useful here
}
}
Then I can call:
observable(1)(2);
Upvotes: 0