Hello-World
Hello-World

Reputation: 9545

nested this is pointing to the wrong variable

In the class below

The this in new SeatReservation("Steve", this.availableMeals[0]), is refering to inside seats , How do I make it refer to the correct one availableMeals

Can I go new SeatReservation("Steve", parent.this.availableMeals[0]),

// Overall viewmodel for this screen, along with initial state
function ReservationsViewModel() {
    //var self = this;

    // Non-editable catalog data - would come from the server
    this.availableMeals = [
        { mealName: "Standard (sandwich)", price: 0 },
        { mealName: "Premium (lobster)", price: 34.95 },
        { mealName: "Ultimate (whole zebra)", price: 290 }
    ];    

    // Editable data
    this.seats = ko.observableArray([
        new SeatReservation("Steve", this.availableMeals[0]),
        new SeatReservation("Bert", this.availableMeals[0])
    ]);

    // Operations
    this.addSeat = function() {
        self.seats.push(new SeatReservation("", this.availableMeals[0]));
    }
}

Upvotes: 0

Views: 49

Answers (2)

Johannes Egger
Johannes Egger

Reputation: 4041

It should work with this too, because you didn't switch context. Maybe there is something wrong with the binding in the HTML. I created a JS Fiddle which may hopefully help you out.

EDIT: Ahh, if you mean the statement within addSeat, you really need the self variable, or you apply the correct object as this:

this.addSeat = function() {
    this.seats.push(new SeatReservation("", this.availableMeals[0]));
}.apply(this);

Upvotes: 1

epascarello
epascarello

Reputation: 207501

Use the self variable you commented out

self.availableMeals[0]

Upvotes: 5

Related Questions