Patrick D
Patrick D

Reputation: 6849

KnockoutJS data-binding use instanceof on RequireJS modules

I am building a set of RequireJS AMD module objects. I am using KnockoutJS in order to data-bind a user interface to these modules.

I define my Module:

define([
   "libs/knockout",
], function(ko) {
   MyModuleClass= function() { /* Stuff */ }

   return MyModuleClass;
});

In my View (HTML), I have a data binding:

<span data-bind="if: (myObservable() instanceof MyModuleClass)">
     <!-- Stuff -->
</span>

The goal is to show the markup when the observable is an instance of the MyModuleClass. Otherwise, I do not want to show that markup.

The issue occurs because: since my ViewModel is using RequireJS to load the MyModuleClass as a scope variable in my ViewModel, the KnockoutJS binding does not have a reference to the MyModuleClass. This results in the data-bind failing because MyModuleClass is undefined in that scope. MyModuleClass also has other Modules that derive from it, so the instanceof call is fairly important as I still want child objects deriving from MyModuleClass to pass this data-bind as well.

Are there any recommendations to solving this problem cleanly? I could create computed variables that I can bind off of. Those computed observables could use the instanceof logic, which would remove the dependency from the data-bind tag. This is my best idea I have so far - but I'm not sure if it's as clean as I would like it to be.

Any clean way to achieve similar functionality that is contained entirely within the data-bind tag would be my goal.

Upvotes: 1

Views: 370

Answers (1)

artm
artm

Reputation: 3678

The issue occurs because: since my ViewModel is using RequireJS to load the MyModuleClass as a scope variable in my ViewModel, the KnockoutJS binding does not have a reference to the MyModuleClass.

You're overthinking it, the issue has nothing to do with RequireJS. MyModuleClass isn't in the binding context hence it isn't available for the binding. Add it to the view model or some other place reachable from the binding context and it will be available. E.g., in the view model:

// require and export MyModuleClass
var MyModuleClass = this.MyModuleClasss = require("my-module-class");

Upvotes: 1

Related Questions