dmackerman
dmackerman

Reputation: 2966

KnockoutJS: nesting ko.observableArray

I'm trying to decide on the best way to structure my application, and I'm getting a bit confused. I want my basic structure to be something like this:

banners (ko.observableArray)
   - banner 
       - previewURLs (ko.observableArray)

The way that I'm creating the "banner" is by defining it as a class like so:

// define a "banner" class
function banner(inventory, name, advertiser, artType, artSize, previewURLs) {
    return {
        inventory : ko.observable(inventory),
        name : ko.observable(name),
        advertiser : ko.observable(advertiser),
        artType : ko.observable(artType),
        artSize : ko.observable(artSize),
        previewURLs : ko.observableArray(previewURLs),

        // track if our banner is selected
        isSelected : ko.observable(false),  
    };
};

Is this the correct method? I'm not sure how to "nest" the "previewURLs" array in the banner itself. I tried doing it above but that doesn't seem to work.

Then in my viewModel:

var viewModel = {
    selectAll: ko.observable(false),
    banners : ko.observableArray([
        new banner("network", "Banner #1", "Target and Friends", "3rd Party", "300x250"), 
        new banner("oo", "Banner #2", "IBM", "Flash", "720x90")
    ]),
    previewURLs : ko.observableArray([
        new previewURL("test site #1", "http://www.google.com"),
        new previewURL("test site #2", "http://www.google.com")
    ]),
    addBanner : function() {
        this.banners.push(new banner("network", "Banner"));
    }
};

Overally, I'm just confused on how to structure it. I've never worked with any MVVM or MVC structure before, so this is all kind of new to me.

My thinking is that I'd be able to access my banners previewURLs by doing something like banners.banner.previewURL(1), but I may be way off in that thinking.

Can I just define a new previewURL inside of the definition for a new banner?

Upvotes: 1

Views: 3801

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

I think that you have the right idea. viewModel.previewURLs can't be accessed until your viewModel object has been created though. You would likely want to pass your previewURLs into the banner constructor function or store your previewURLs in a previously defined variable that can be accessed within the banner constructor.

Sample of passing in previewURLs here: http://jsfiddle.net/rniemeyer/bZhCk/

Upvotes: 3

Related Questions