嵌套这是指向错误的变量

时间:2013-04-19 14:03:48

标签: javascript knockout.js

在下面的课程中

this中的new SeatReservation("Steve", this.availableMeals[0]),指的是seats内部,如何让它引用正确的availableMeals

我可以去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]));
    }
}

2 个答案:

答案 0 :(得分:5)

使用您注释掉的self变量

self.availableMeals[0]

答案 1 :(得分:1)

它也应该与this一起使用,因为你没有切换上下文。也许HTML中的绑定有问题。我创建了一个JS Fiddle,可能会帮助你。

编辑:啊,如果你的意思是addSeat中的陈述,你真的需要self变量,或者你将正确的对象应用为this

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