1

I am going through the tutorial from the official website:

Knockout single page application lesson

this is the view:

<!-- Folders -->
<ul class="folders" data-bind="foreach: folders">
    <li data-bind="text: $data, 
                   css: { selected: $data == $root.chosenFolderId() },
                   click: $root.goToFolder"></li>
</ul>

and the script:

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 dont' t understand 2 things:

  1. the 'click:' event is calling the javascript function goToFolder, however, with no argument, how does it know which folder is clicked to set the chosenFolderId ?

  2. Correct me if I am wrong, the line css: { selected: $data == $root.chosenFolderId() } means if the current selected object $data is equal to chosenFolderId(), therefore the css with the name selected is enable ?

Cheers all

1 Answer 1

2

Here are answers:

  1. By default knockout passes current context to the function that is called. In your case this is $data object which contains one of the following strings 'Inbox', 'Archive', 'Sent', 'Spam'.

  2. Yes, you are right. This means that selected css class will be applied to the <li> element where $data is equal to chosenFolderId property of view model.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Artem, thanks a lot, I understand better why the function is called with no argument, About the syntax, why the css: is called with the () of the end of chosenFolderId() ?, and click: without ?
Because you should use brackets when you have an expression in binding (i.e. "visible: Something() > 10"), if you have just function or observable you don't need to put brackets. This article help you to understand basic things: knockmeout.net/2011/06/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.