dmathisen
dmathisen

Reputation: 2342

Creating a KnockoutJS observable with dynamic name

I'm using my own simple templating system for my app and will be loading an unknown number of the 'same' templates per page.

So basically, I grab some data via an ajax call and get a uniqueId. I'm then loading a template into my page and applying ids and a data-bind="with: " using the uniqueId.

<div id="content-uniqueId">
    <div data-bind="with: uniqueId">
        ...
    </div>
</div>

Then I call a function and am trying to create an observableArray using the uniqueId, so that it binds to my 'with'.

Something like:

function(uniqueId) {
     var theObservable = uniqueId;
     theObservable = ko.observableArray(); // make the observable name equal to uniqueId
     // get some data
     theObservable(new data);
}

I've created a JS Fiddle to help clear things up but it won't work because I'm not getting ajax data or passing a unique id.

JS Fiddle here

EDIT:

Updated JS Fiddle, per Tyrsius' suggestion below.

this[uniqueId] = ko.observableArray(new entityApp.dataContext.EntityModel(data));

Definitely one step close, but I'm getting an error:

The argument passed when initializing an observable array must be an array, or null, or undefined

But 'new entityApp.dataContext.EntityModel(data)' returns an object array, so it should be fine.

Upvotes: 3

Views: 3621

Answers (1)

Kyeotic
Kyeotic

Reputation: 19847

Javascript makes dynamic assignment and reflection simple with its object indexer:

var ViewModel = function(propName) {
    this[propName] = ko.observable("reflection");
};

ko.applyBindings(new ViewModel("dynamic"));

Here is a fiddle demonstrating the binding.

Upvotes: 3

Related Questions