Note that there are some explanatory texts on larger screens.

plurals
  1. POKnockout JS - viewModel access
    primarykey
    data
    text
    <p>I'm writing an application for making a reservation. The reservation procedure is rather complex and has quite some dependencies so I decided to use knockout to help me observe changes and update the UI.</p> <p>I started implementing the customer list. The first customer in the form will be the one who has to enter his details, the others only need names. I figured I could just add a dependentObservable that checks if the current customer is the first one in the customers array to decide whether to display the additional fields.</p> <p>The problem is that when trying to access viewModel from a customer, I get only get 'undefined'. I tried passing a reference to viewModel to the customer, but that didn't work either. What am I doing wrong? Can viewModel not be accessed?</p> <p>Here's the code:</p> <pre><code>var customer = function(){ this.firstName = ko.observable(''); this.lastName = ko.observable(''); this.fullName = ko.dependentObservable( function(){ return this.firstName() + " " + this.lastName(); }, this ); this.gender = ko.observable(''); this.diet = ko.observable(''); this.primaryCustomer = ko.dependentObservable( function(){ console.log(viewModel); return viewModel.customers.indexOf(this) == 0; }, this ); this.email = ko.observable(''); } var viewModel = { customers: ko.observableArray([new customer()]), addCustomer: function(){ this.customers.push(new customer()); }, removeCustomer: function(customer){ this.customers.remove(customer); } } ko.applyBindings(viewModel); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload