0

I have the following javascript object which I use as an enum.

Object {Group1: 0, Group2: 1, Group3: 2, Group4: 3, Group5: 4}

Id like to be able to use it to create check boxes or drop downs using knockout templates basicly i need these values to be observable.

Ive tried adding the object to an observable array but it doesnt work. can any one help?

1 Answer 1

1

You can use a computed observable for that.

function ViewModel(){
   var obj = {Group1: 0, Group2: 1, Group3: 2, Group4: 3, Group5: 4}; // Your object

   this.data = ko.computed(function(){
      // works on modern browsers (keys/map), old ones would need 
      // a shim or for in loop
      return Object.keys(obj).map(function(elem){ 
          return {val:elem+" -> "+obj[elem]};
       });
   });
}

ko.applyBindings(new ViewModel());

Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

this makes the drop down lag.
@666 uhh, what? I don't understand what you mean by that, or what you're trying to do. My solution is how you'd normally do what you asked for. If the data doesn't change - don't make it a computed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.