Mike Flynn
Mike Flynn

Reputation: 24315

Iterate javascript properties for knockout.js observables to create a subscription

Is there a way to iterate properties on a javascript object and test for an observable so I can create a subscription on it? Below is just a simple example but my object has about 30 properties.

var name = {
   firstName: ko.observable(),
   lastName: ko.observable()
};

// Iterate properties and test for observable to create subscription on.

lastName.subscribe(function(s) {
   // modified
);

firstName.subscribe(function(s) {
   // modified
);

Upvotes: 0

Views: 46

Answers (2)

Nathan Fisher
Nathan Fisher

Reputation: 7941

Something like this. This way you have a list of subscribed objects that you can unsubscribe from later in code.

var nameTest = {
  salutation: "Hi",
  firstName: ko.observable("Test"),
  lastName: ko.observable("Person")
};

var subscribedObjects = Object.values(nameTest)
  .filter(item => ko.isObservable(item))
  .map(observableItem => observableItem.subscribe(newValue => console.log(newValue)));

ko.applyBindings(nameTest);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="with: nameTest">
  <input type="text" data-bind="textInput: salutation" />
  <input type="text" data-bind="textInput: firstName" />
  <input type="text" data-bind="textInput: lastName" />

</div>


<div data-bind="with: nameTest">
  <span data-bind="text: salutation"></span>
  <span data-bind="text: firstName"></span>
  <span data-bind="text: lastName"></span>
</div>

Upvotes: 1

Akrion
Akrion

Reputation: 18515

You can Object.values on the name object and for anything which is ko.isObservable subscribe:

Object.values(name).forEach(v => {
  if(ko.isObservable(v))
    v.subscribe(() => { console.log("Do the cha cha") })
}) 

You can see it working here

If you want to keep a list then just filter on ko.isObservable:

let subs = Object.values(name).filter(ko.isObservable) 

Then subscribe or unsubscribe later.

subs.forEach(v => v.subscribe(() => { console.log("Did the cha cha") }))

Upvotes: 2

Related Questions