KO.js如何在使用视图构造函数时设置默认视图 [英] KO.js howto set default view when using view constructor

查看:79
本文介绍了KO.js如何在使用视图构造函数时设置默认视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我(是KO新手)正在玩Ryan Niemayer提供的视图构造函数:

index.html:

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

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

在加载时,selectedView是不确定的,但是当我单击选择时,它包含了预期的对象……

我还尝试将viewModel重构为一个函数,尝试将参数提供给html声明,以及一些随机的猜测工作,它们的一致性不足以在此处进行总结……

有什么建议吗? TIA!

解决方案

实际上您缺少()

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

这里有用的小提琴: http://jsfiddle.net/ZAHC9/

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/

这篇关于KO.js如何在使用视图构造函数时设置默认视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆