0

I have created and registered a widget in Durandal, so now I am able to use it in other views using this markup:

<div data-bind="MyWidget: { activationData }" />

I would like to call methods on that widget from the parent view model, for example:

ParentViewModel.prototype.buttonClick = function() {

    this.myWidget.doSomething();

}

Is there a neat way to access a widget composed in this way from the parent view model?

Matt
  • 3,793
  • 3
  • 24
  • 24

1 Answers1

0

I've been working on this problem since posting the question, and the best solution I have come up with is this:

  • Add an observable, let's call it "myWidget", to the parent view model
  • Pass the empty observable to the widget upon activation, using widget binding
  • During activation, the widget sets the parent's observable to itself

For example, in the View Model definition:

this.myWidget = ko.observable(null);

Use widget binding in the parent view:

<DIV data-bind="MyWidget: { theirWidget : myWidget }" />

Set the parent view's reference in the widget's activate method:

 MyWidget.prototype.activate = function(activationObject) {

    activationObject.theirWidget(this);

 }

While this is a reasonable solution, I'll wait and see whether anyone else provides an alternative before accepting this answer.

Matt
  • 3,793
  • 3
  • 24
  • 24