gpt4 book ai didi

jquery - 在多个页面中使用 KnockoutJS

转载 作者:行者123 更新时间:2023-12-01 00:07:47 26 4
gpt4 key购买 nike

我刚刚开始学习 KnockoutJS。我感到困惑的一件事是,这些示例似乎都集中在具有单个 View 模型的单个 View 上。更大的应用程序如何工作?

我将编写一个纯 html/jquery 应用程序。所有数据均通过 ajax 以 json 形式提供。应用程序顶部有一个通用的导航标题,其中包含使用 Twitter Bootstrap 实现的多个选项卡和子选项卡。

如果我将应用程序的每个页面构建为单独的 html View 和 js View 模型,如何维护单个统一 header ?如果这是服务器端 asp.net webforms,我会使用母版页。但这都是客户端。

Knockout 中有什么东西可以处理这个问题吗?或者也许另一个库可以解决这个特定问题?

我想我可以在一个大的 html 页面中编写应用程序,但它会相当大。必须有更好的方法。

最佳答案

您绝对可以将 View 模型分开。在 ko.applyBindings 方法中,第一个参数是 View 模型,但第二个可选参数是要将该 View 模型绑定(bind)到的 dom 元素。

我没有仔细研究 Twitter Bootstrap,但我设置了 jsfiddle,它应该能让你顺利起步:http://jsfiddle.net/JasonMore/ygT6v/10/

查看

<ul id="menu" data-bind="foreach:options">
<li data-bind="text:option"></li>
</ul>
<br/>
<section id="person">
<p>Hey, <span data-bind="text:fullName"></span>, what are you doing?</p>
<p><label>First: <input type="text" data-bind="value:firstName" /></label></p>
<p><label>Last: <input type="text" data-bind="value:lastName" /></label></p>
</section >
<br />
<section id="address">
<p>You live at: <span data-bind="text:fullAddress "></span></p>
</section >

Javascript

// main.js
var menuViewModel = {
options: ko.observableArray([
{ option: 'person'},
{ option: 'address'}
])
};

ko.applyBindings(
menuViewModel,
document.getElementById('menu')
);

// person.js
var personViewModel = new function() {
var self = this;
this.firstName = ko.observable('John');
this.lastName = ko.observable('Doe');
this.fullName = ko.computed(function() {
return self.firstName() + ' ' + self.lastName();
});
};

ko.applyBindings(
personViewModel,
document.getElementById('person')
);

// address.js
var addressViewModel = new function() {
var self = this;
this.address = ko.observable('123 main');
this.city = ko.observable('Smallville');
this.state = ko.observable('TX');
this.zip = ko.observable('12345');
this.fullAddress = ko.computed(function() {
return self.address() + ' ' + self.city() + ' ' + self.state() + ' ' + self.zip();
});
};

ko.applyBindings(
addressViewModel,
document.getElementById('address')
);

关于jquery - 在多个页面中使用 KnockoutJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10326062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com