Veikedo
Veikedo

Reputation: 1503

knockoutjs execute callback immediately after subscribe to observable

I have:

    this.selectedItem.subscribe(model => {
        this.currentEditor(this.editors.find(e => e.canRender(model)));
        this.currentEditor().render(model);
    });

where this.selectedItem already has a value.

Is it possible to run callback (but leaving it anonymous) immediately after subscribing?

Upvotes: 1

Views: 476

Answers (2)

nemesv
nemesv

Reputation: 139758

You can call valueHasMutated on this.selectedItem, so

this.selectedItem.valueHasMutated()

However this not just runs your callback but also notify everybody else, e.g bindings, computeds etc.

So you are propably better to have a named function and call it when it is needed and use that also in the subscribe.

Upvotes: 1

TSV
TSV

Reputation: 7641

You can extract function into a variable and call it:

var changeHandler = (model) => {
    this.currentEditor(this.editors.find(e => e.canRender(model)));
    this.currentEditor().render(model);
};
this.selectedItem.subscribe(changeHandler);
changeHandler();

Upvotes: 0

Related Questions