[英]Extend javascript generic view model. (Knockout)
Context: I'm quite new to what I like to think of as, "serious javascript/jquery coding", my previous attempts would probably be considered treason :P. 上下文:对于“严重的javascript / jquery编码”,我很陌生,我以前的尝试可能被认为是叛国性:P。
My question: I've noticed a pattern in some of our client side view models and would like to consolidate some of them into a single .js file. 我的问题:我注意到一些客户端视图模型中的模式,并希望将其中一些合并到单个.js文件中。
Everything seems to be working for most scenarios, except for the screens where i'd need to create an additional set of observables, that don't necessarily map to my JS object returned from the server. 一切似乎都适用于大多数情况,除了需要创建一组额外的可观察对象的屏幕,这些屏幕不一定映射到服务器返回的JS对象。
var AdminPages = AdminPages || {};
AdminPages.SimplePageVM: function (options) {
var self = this;
self.hasChanges = function () {};
self.isValid = function () {};
// CRUD Actions
self.get = function () {
$.ajax({
url: options.getUrl,
dataType: 'json',
data: !$.isEmptyObject(options.someId) ? { someId: options.someId} : null,
success: function (result) {
self.observables = ko.mapping.fromJS(result);
ko.editable(self.observables);
ko.applyBindings(self, $('form')[0]);
},
error: function (result) {}
});
};
self.save = function () {};
self.edit = function () {};
self.cancel = function () {};
// Initialise the viewmodel on create
self.get();
}
Id like to add the following to the view model. 我想在视图模型中添加以下内容。 I'm thinking i need to create an entirely new object, (as self.observables only get created on the success of the get function), and then add my new object and its properties on item bind.
我在想我需要创建一个全新的对象(因为self.observables仅在成功获得get函数时创建),然后在项目绑定上添加我的新对象及其属性。
what id like to add: 想要添加什么ID:
self.newObject.IsPercentageEvaluation =
ko.computed(function () {
var isPercentage = self.observables.IsPercentageBased() == 'true';
if (isPercentage) {
self.observables.BalancePercentage('40');
} else {
self.observables.BalancePercentage('');
}
return isPercentage;
});
And to call it all: 并称之为:
$(function () {
var obj = {
IsPercentageEvaluation = ko.computed(...);
};
AdminPages.SimplePageVM({
getUrl: '@Url.Action("Get", "SomeController")',
editUrl: '@Url.Action("Update", "SomeController")',
organisationId: '@ViewBag.OrganisationID',
newObject: obj
});
} ($));
I'd just like to confirm if this is the correct way of approaching this situation? 我只想确认这是否是解决这种情况的正确方法? Or if there is a better way, eg making use of a certain java script pattern, or something to that extent?
或者,如果有更好的方法,例如利用某种Java脚本模式或某种程度的方法?
I worked on a large project last spring and we tried followed a pattern similar to what you are using. 去年春天,我在一个大型项目上工作,我们尝试遵循与您使用的模式类似的模式。
There are issues that need to be considered- 有一些问题需要考虑-
I do like your view model. 我确实喜欢您的视图模型。 It is a flexible and extensible piece of code.
它是一段灵活且可扩展的代码。 I will be borrowing it on our next project.
我将在下一个项目中使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.