KO.js howto set default view when using view const

2019-08-29 00:34发布

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!

标签: knockout.js
1条回答
做自己的国王
2楼-- · 2019-08-29 00:58

Actually you're missing ()

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

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

查看更多
登录 后发表回答