bsr
bsr

Reputation: 58662

Javascript method usage

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,

  1. How can one invoke it by passing an argument like self.chosenFolderId(folder);
  2. Where is folder defines?

If you can just point to an article which explains this that will do.

Thanks.

Upvotes: 0

Views: 110

Answers (3)

Esailija
Esailija

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

Dave Newton
Dave Newton

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

ziad-saab
ziad-saab

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

Related Questions