-1

I am learning Haxe and KnockoutJS, but this simple code doesn't work(you can look this in JSBin). I cannot remove member in the page.

index.html

<table>
    <thead><tr>
        <th>name</th><th></th>
    </tr></thead>
    <tbody data-bind="foreach: seats">
    <tr>
        <td><input data-bind="value: name" /></td>
        <td><a href="#" data-bind="click: $root.removeSeat">Remove</a></td>
    </tr>
    </tbody>
</table>

Main.hx

package ;

import js.Lib;
import knockout.*;

class Main {

    static function main() {
        Knockout.applyBindings(new MemberViewModel());
    }

}

class MemberViewModel {

    public var seats : Dynamic;

    public function new() {
        this.seats = Knockout.observableArray([
            {name: "Steve"}, 
            {name: "Bert"}
        ]);
    }

    public function removeSeat(seat) : Void {
        trace(this.seats);
        this.seats.remove(seat);
    }

}

I cannot understand the reason why this.seats become undefined. Thank you for your help.

2
  • because the context of the function is the seat you clicked on, so if you click remove on Steve this refers to the object {name: "Steve"} Jul 9, 2014 at 3:51
  • In Haxe, this always refers to the class. I tried to change this e.x. var self = this; but the code doesn't work. Jul 9, 2014 at 4:35

1 Answer 1

2

You are losing context, use bind to make the context to be the class

<a href="#" data-bind="click: $root.removeSeat.bind($root)">Remove</a>

JSBin

You lose context when a method is passed as an argument or set to a variable and then invoked. This example will show what I mean better

function someObject(){}
someObject.prototype.someMethod = function(){
   console.log("Context: ",this);
}

var newObj = new someObject();
newObj.someMethod();
//Console will show: Context:  someObject {someMethod: function}
var methodVar = newObj.someMethod;
methodVar();
//Console will show: Context:  Window {...}
function fnCall(method){
   method();
}
fnCall(newObj.someMethod);
//Console will show: Context:  Window {...}

Using bind lets you set the context

fnCall(newObj.someMethod.bind(newObj));
//Console will show: Context:  someObject {someMethod: function}
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.