gpt4 book ai didi

javascript - ASP.NET MVC View 中的 knockout 绑定(bind)

转载 作者:行者123 更新时间:2023-11-28 06:46:02 26 4
gpt4 key购买 nike

在我的应用程序中,我们从 ASP.NET MVC 方法获取 json 数据。并使用数据绑定(bind)来绑定(bind) View 。目前我正在使用 Knockout JavaScript 库 v2.2.1 和 Knockout Mapping 插件 v2.3.5。

因此,每当我加载分部 View 时,我都必须再次调用相同的绑定(bind)方法来绑定(bind)分部 View 中的属性。

因此,如果我将 knockout 库更新到最新版本并再次调用绑定(bind)方法,则会抛出以下错误:

Uncaught Error: You cannot apply bindings multiple times to the same element.

有没有什么方法可以让我们调用一次绑定(bind)方法,然后在分部 View 中绑定(bind)属性而不调用绑定(bind)方法?或者我必须更改什么才能使用新的库版本?

我目前使用的方法来绑定(bind)数据并在每次加载部分 View 时调用

function getResourceFile(CallBack) {
var Menu = function (data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
};

if (typeof localStorage === 'object') {
try {
// Geeting language and localize application on this behalf STARTED
var lang = localStorage.getItem('lan');
var userLang = '';
if (lang === null || lang === 'undefined' || lang === '') {
userLang = window.navigator.language || window.navigator.userLanguage;
if (typeof userLang == 'undefined')
userLang = "en";
}
else {
userLang = lang;
}

//userLang = "en";//comment this
if (userLang.toString().length == 2) {
if (userLang == 'de') { CurrentLocale = "de-DE"; }
else { CurrentLocale = "en-US"; }
}

var l_lang = $.trim(userLang.substr(0, 2));
var currentURL = document.URL;
if (currentURL.indexOf("SelectApp/de") != -1) {
userLang = 'de';
CurrentLocale = "de-DE";
l_lang = 'de';
}
else if (currentURL.indexOf("SelectApp/en") != -1) {
userLang = 'en';
CurrentLocale = "en-US";
l_lang = 'en';
}

var jsonName = endpoints.CPRes + l_lang;
localStorage.setItem('lan', userLang);

$.getJSON(jsonName, function (data) {
LocalizationViewModel = data;
ko.applyBindings(new Menu(data));
CallBack && CallBack();
});

} catch (e) {
Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype.setItem = function () { };
alert('Your web browser does not support storing settings locally. In Safari, the most common cause of this is using "Private Browsing Mode". Some settings may not save or some features may not work properly for you.');
}
}

}


function BindDataViewModel() {
if (LocalizationViewModel === null || LocalizationViewModel === 'undefined' || LocalizationViewModel === '') {
getResourceFile();
} else {
//var localdeferred = $.Deferred();
var t = setTimeout(function () {
ko.applyBindings(LocalizationViewModel);
// localdeferred.resolve();
}, 300);
//return localdeferred;
}
}

最佳答案

您可以指定要绑定(bind)的 DOM 元素作为 ko.applyBindings 的第二个参数,而不是绑定(bind)到整个屏幕。

为了避免“ Uncaught Error :您不能将绑定(bind)多次应用于同一元素。”您可以在部分上指定一个元素 id 以便将数据绑定(bind)到

ko.applyBindings(LocalizationViewModel, document.getElementById(elementId)

哪里elementId是局部 View 上元素的唯一 ID。

关于javascript - ASP.NET MVC View 中的 knockout 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33413266/

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