KO.js howto set default view when using view constructor

I'm (new to KO!) playing with the view constructor offered by Ryan Niemayer here: How to properly structure a KnockoutJS application, and I'm trying to set a default view to show on load…

For example in #3, you can use a constructor function like…

and here is my fork attempting to set the default:

// (templates are defined in the fiddle)
var View = function(title, templateName, data) {
   this.title = title;
   this.templateName = templateName;
   this.data = data; 
};

var definedViews = ko.observableArray([
    new View("one", "oneTmpl", new SubModelA()),
    new View("two", "twoTmpl", new SubModelB())
]);

var viewModel = {
    views: definedViews,
    defaultView: 0,
    selectedView: ko.observable( definedViews[0] )
};

ko.applyBindings(viewModel);

index.html:

    <!-- ko with: selectedView -->
    <div data-bind="template: { name: templateName, data: data }"></div>
    <!-- /ko -->

http://jsfiddle.net/memeLab/WVVyM/2/

on load, selectedView is undefined, but when i've clicked to select, it contains an object as expected…

I've also tried refactoring the viewModel as a function, trying to feed parameters to the html declaration, and a bunch of random guesswork not coherent enough to summarise here…

any suggestions? TIA!


Actually you're missing ()

var viewModel = {
    views: definedViews,
    defaultView: 0,
    selectedView: ko.observable( definedViews()[0] )
};

Here the working fiddle: http://jsfiddle.net/ZAHC9/

链接地址: http://www.djcxy.com/p/66058.html

上一篇: iOS AVFoundation:如何从mp3文件中获取作品?

下一篇: KO.js如何在使用视图构造函数时设置默认视图