我有 2 个 View 模型,一个是标题仪表板,一个只是一个在线存钱 jar 。我想使用从一个 js 文件到另一个文件的函数。我从仪表板中取出个人资料图片 url 并放入我的 div。
<a class="icon-box permission desktop" data-local-storage="image" id="changeAvatarHeader" href="@Url.Action("Profile", "User")" data-bind="style: { backgroundImage: 'url(\'' + Header().ProfileImage() + '\')' }">
二
<div class="piggy-user-profile-icon" data-local-storage="image" href="@Url.Action("Profile", "User")" data-bind="style: { backgroundImage: 'url(\'' + HeaderModel().ProfileImage() + '\')' }"></div>
问题是 profileImage 在我的第二个 viemodel 中未定义。
function DashboardViewModel() {
var self = this;
self.searchModel = new AuthorizedSearchViewModel();
self.Header = ko.observable(new HeaderModel());
self.UnSeenMessagesCount = ko.observable(0);
self.Messages = ko.observableArray();
self.CanShowRemindProfile = ko.observable(false);
self.Remind = ko.observable(new RemindModel());
self.LoadUserInformation = function () {
$.post('/User/GetUserInfoForDashboardHeader',
function (response) {
InitTawkChat(response);
self.Header(new HeaderModel(response));
}, "json").done(function () { console.warn("loaderOff") });
}
我在仪表板中使用的数据函数已经在那个页面上使用了,所以我不能在我的 piggybankjs 中再写一个,它会读取配置文件数据两次。
function HeaderModel (data) {
var self = this;
self.Balance = ko.observable();
self.Name = ko.observable();
self.ProfileImage = ko.observable('');
self.CompleteLevel = ko.observable();
}
我只是想把ProfileImage拿出来
最佳答案
有多种方法可以做到这一点,但通常您会将公共(public)数据从 View 模型中移出到一个单独的对象中,您可以在任何需要使用它的地方引用该对象。您可以看到运行 here 的一个基本示例:
var globalState = {
user: {
name: ko.observable(),
picture: ko.observable()
}
}
var DashboardViewModel = function() {
this.loadUserInformation = function() {
globalState.user.name("Ozzy Osbourne");
};
};
var BankViewModel = function() {
this.ammount = ko.observable((20).toFixed(2));
};
ko.applyBindings(new DashboardViewModel(), document.getElementById('dashboard'));
ko.applyBindings(new BankViewModel(), document.getElementById('bank'));
HTML:
<div id="dashboard">
Hello, <span data-bind="text: globalState.user.name"></span>!
<button data-bind="click:loadUserInformation">
load user
</button>
</div>
<div id='bank'>
<span data-bind="text: globalState.user.name"></span>, you have <span data-bind="text: ammount"></span>!
</div>
关于javascript - 对 2 个不同的 View 模型使用一个函数 KnockoutJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52630387/