Skip to content

Change "this" in execute and canExecute callbacks #23

Open
@rmja

Description

@rmja

Feature request.

In knockout computed observables it is possible to change the value of "this" in the read/write callbacks by settings the owner option when defining the computed observable.
Something like this:

aComputed = ko.computed({read: getComputed, owner: someObject});

It would be nice with a similar definition in ko.command and ko.asyncCommand.
For example:

aCommand = ko.command({execute: a, owner: someObject});

This feature is particularly interesting when working with typescript. Here "this" is only defined in the constructor, so unless you want to write all command implementations in the constructor, it is needed to pass "this" from here to the command callback.
For example:

enterCommand;

constructor() {
this.enterCommand = ko.command({ execute: enter, owner: this });
}

enter() {
"this" is now the viewmodel and not window.
}

The implementation is fairly simple. I have made it by including:
owner = options.owner || this,
in the top of the two command types, and then invoke the callbacks with this context with canExecuteDelegate.apply(owner, [self.isExecuting()]) and changed "this" to "owner" in executeDelegate.apply(owner, args).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions