简体   繁体   English

扩展javascript通用视图模型。 (昏死)

[英]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- 有一些问题需要考虑-

  • Inside your ajax.success function, we routinely needed ability to modify the returned view mode. 在您的ajax.success函数内部,我们通常需要具有修改返回的视图模式的功能。 For example, add ko.computed's. 例如,添加ko.computed的。 I would suggest that you add an overrideable function for this that you call before the ko.applybindings. 我建议您为此添加一个可覆盖的函数,以便在ko.applybindings之前调用它。
  • You need ability to handle situation where your application has a problem returning the data. 您需要能够处理应用程序返回数据时遇到的问题。 For example, database is down or a web service is offline. 例如,数据库已关闭或Web服务处于脱机状态。 You need to have a graceful way of handling these situations. 您需要以一种优雅的方式来处理这些情况。 We did this by extending our view model so that these conditions were returned on separate properties. 我们通过扩展视图模型来做到这一点,以便这些条件在单独的属性中返回。
  • If you are returning row data to be displayed in table data, you may have to modify your ajax.success function to handle an array of data. 如果要返回要在表数据中显示的行数据,则可能必须修改ajax.success函数以处理数据数组。 We always seemed to run into issues with this. 我们似乎总是遇到这个问题。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM