TypeScript and Knockout binding to 'this'

2019-01-13 05:28发布

I've been creating a htmlHelper function using TypeScript and KnockoutJS to edit a list of emails.

The list of emails is a Knockout ObservableArray called emails, and I have a link against each item to delete them. This is the HTML fragment:

   <ul data-bind="foreach: emails" >
        <li>
            <a href="#" data-bind="click: $parent.deleteItem">Delete</a>
            &nbsp;<span data-bind="text: $data"></span>
        </li>
    </ul>

The delete link is bound to $parent.deleteItem this is a method in the viewmodel:

// remove item
public deleteItem(emailToDelete: string) {
    // remove item from list
    this.emails.remove(emailToDelete);
}

This all works until the deleteItem method is executed. The "this" in this method when it is called is the item in the array, and not the view model. Hence this.emails is a null reference and fails.

I know that TypeScript supports the Lambda syntax but I can't find the right way to write this (there few examples out there).

Or is there a different approach I could take?

8条回答
我命由我不由天
2楼-- · 2019-01-13 06:07
declare class Email { }
declare class ObservableArray {
    remove(any): void;
}

class MyViewModel {
    public emails : ObservableArray;

    constructor() {
        Rebind(this);
    }

    public deleteItem(emailToDelete: Email) {
        this.emails.remove(emailToDelete);
    }
}

function Rebind(obj : any)
{
    var prototype = <Object>obj.constructor.prototype;
    for (var name in prototype) {
        if (!obj.hasOwnProperty(name)
                && typeof prototype[name] === "function") {
            var method = <Function>prototype[name];
            obj[name] = method.bind(obj);
        }
    }
}

You might want a polyfill for Function.bind():

// Polyfill for Function.bind(). Slightly modified version of
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind#Compatibility
if (typeof Function.prototype.bind !== "function") {
    Function.prototype.bind = function(oThis) {
        if (typeof this !== "function") {
            // closest thing possible to the ECMAScript 5 internal IsCallable function
            throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
        }

        var aArgs = <any[]> Array.prototype.slice.call(arguments, 1),
            fToBind = this,
            fNOP = function() {},
            fBound = function() {
                return fToBind.apply(this instanceof fNOP && oThis ? this: oThis, aArgs.concat());
            };

        fNOP.prototype = this.prototype;
        fBound.prototype = new fNOP();

        return fBound;
    };
}
查看更多
ら.Afraid
3楼-- · 2019-01-13 06:07

My final solution is a base class, that rebinds all prototype functions to itself on constructor. Much like Markus Jarderot's solution.

class BaseClass {
    constructor() {
        for (var i in this) {
            if (!this.hasOwnProperty(i) && typeof (this[i]) === 'function' && i != 'constructor') {
                this[i] = this[i].bind(this);
            }
        }
    }
}

Advantages:

  • All subclasses are forced to call super constructor, which is the behavior I wanted.
  • When the rebind code is executed, there are only prototype functions in the object (variables are added later).
  • It avoids the creation of big functions on every object. Only a small proxy function is created per object when you call bind.
  • Better organization of class code by not putting functions on constructor.
  • Any function can be used as a callback, you don't need to change the code when a function is called from an event.
  • You don't have the risk of binding functions twice.
  • It is better to bind the function only once, instead doing it in the view every time the click/event binding is executed.

PS:
You still will need the bind polyfill.
I'm using typesript 0.9.5

查看更多
一纸荒年 Trace。
4楼-- · 2019-01-13 06:11

I was inspired by the bind answer and came up with this, I think it a little easier to read.

<a href="#" data-bind="click: function () {$parent.deleteItem()}">Delete</a>

Wrap the method in a lambda/anonymous function. Don't forget the ().

查看更多
Root(大扎)
5楼-- · 2019-01-13 06:13

to add my 2 cents, there's also a dirty way, that leverages the variable _this created by the Typescript compiler to keep a reference on this :

public deleteItem(emailToDelete: string) {
    var that = eval('_this');
    // remove item from list
    that.emails.remove(emailToDelete); // remove? in JS,  really? 
}
查看更多
做自己的国王
6楼-- · 2019-01-13 06:14

Use data-bind something like this:

data-bind="click:$parent.deleteItem.bind($parent)"

Assign this to that as shown below

public deleteItem(itemToDelete) 
{
    var that = this;
    // remove item from list
    that.emails.remove(itemToDelete); 
}
查看更多
7楼-- · 2019-01-13 06:16

Although I prefer Markus' solution, here's what I have used before to work around this issue:

public fixThis(_this, func) {
    return function () {
        return _this[func].apply(_this, arguments);
    };
}

<a href="#" data-bind="click: fixThis($parent, 'deleteItem')">Delete</a>

Note that additional arguments can be passed to the method by adding them after the name of the method:

fixThis($parent, 'deleteItem', arg1, arg2);
查看更多
登录 后发表回答