knockout.js嵌套对象中的多个映射

时间:2017-08-01 14:13:49

标签: javascript knockout.js

我是knockout.js的新手,我不知道如何使用我的对象进行多次映射。 那是来自服务器的数据:

var persons = {
    'value': [
        {
            "id": "1",
            "civility": "Mr.",
            "firstname": "john",
            "lastname": "doe",
            "phone": "00 00 00 00 00",
            "email": "email@email.com",
            "contract": [
                {
                    "id": "1",
                    "gamme": "Gamme 1",
                    "formula": "Formula 1"
                },
                {
                    "id": "2",
                    "gamme": "Gamme 2",
                    "formula": "Formula 2"
                }
            ]
        }
    ]
}

我对整个对象进行了第一次映射,然后计算了一些数据:

var person_mapping = {
        'value': {
            create: function (options) {
                if (options.data != null) {
                    return new myPersonModel(options.data);
                }
            }
        }
    }

var myPersonModel = function (data) {
        ko.mapping.fromJS(data, {}, this);

        this.fullName = ko.computed(function () {
            return this.civility() + ' ' + this.lastname() + ' ' + this.firstname();
        }, this);
    }

执行此操作后,我得到了我想要的第一部分:

self.dataModel = ko.mapping.fromJS(persons, person_mapping);

但是现在,我想对person对象中的contract数组做同样的事情,也就是说应用一个映射并做一些像这样的ko.computed:

var contract_mapping = {
            'contract': {
                create: function (options) {
                    if (options.data != null) {
                        return new myContractModel(options.data);
                    }
                }
            }
        }

var myContractModel = function (data) {
            ko.mapping.fromJS(data, {}, this);

            this.contractName = ko.computed(function () {
                return this.gamme() + ' ' + this.formula();
            }, this);
        }

但我不知道如何应用我的第二个映射,似乎没什么用。

1 个答案:

答案 0 :(得分:3)

您可以在An error occurred while starting the application. ArgumentException: Keyword not supported: '"server'. System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary<string, string> parsetable, string connectionString, bool buildChain, Dictionary<string, string> synonyms) ArgumentException: Keyword not supported: '"server'. System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary<string, string> parsetable, string connectionString, bool buildChain, Dictionary<string, string> synonyms) System.Data.Common.DbConnectionOptions..ctor(string connectionString, Dictionary<string, string> synonyms) System.Data.SqlClient.SqlConnectionString..ctor(string connectionString) System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(string connectionString, DbConnectionOptions previous) System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, ref DbConnectionOptions userConnectionOptions) System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) System.Data.SqlClient.SqlConnection.set_ConnectionString(string value) Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection.CreateDbConnection() Microsoft.EntityFrameworkCore.Internal.LazyRef.get_Value() Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open() Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerDatabaseCreator+<>c__DisplayClass11_0.<Exists>b__0(DateTime giveUp) Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute<TState, TResult>(Func<TState, TResult> operation, Func<TState, ExecutionResult<TResult>> verifySucceeded, TState state) Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute<TState, TResult>(IExecutionStrategy strategy, Func<TState, TResult> operation, TState state) Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated() ContosoUniversity.Data.DbInitializer.Initialize(SchoolContext context) in DbInitializer.cs - namespace ContosoUniversity.Data { public static class DbInitializer { public static void Initialize(SchoolContext context) { context.Database.EnsureCreated(); // Look for any students. if (context.Students.Any()) { return; // DB has been seeded } var students = new Student[] ContosoUniversity.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SchoolContext context) in Startup.cs - app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); DbInitializer.Initialize(context); } } } System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app) Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication() Show raw exception details System.ArgumentException: Keyword not supported: '"server'. at System.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms) at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms) at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) at System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerConnection.CreateDbConnection() at Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value() at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open() at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass11_0.<Exists>b__0(DateTime giveUp) at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](Func`2 operation, Func`2 verifySucceeded, TState state) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, Func`2 operation, TState state) at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreated() at ContosoUniversity.Data.DbInitializer.Initialize(SchoolContext context) in C:\Users\iderlich\OneDrive\Documentos.Kerberos\Practica MVC\VS2017 PC Talca\ContosoUniversity\ContosoUniversity\Data\DbInitializer.cs:line 10 at ContosoUniversity.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SchoolContext context) in C:\Users\iderlich\OneDrive\Documentos.Kerberos\Practica MVC\VS2017 PC Talca\ContosoUniversity\ContosoUniversity\Startup.cs:line 62 --- End of stack trace from previous location where exception was thrown --- at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.Configure(IApplicationBuilder app) at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication() .NET Core X64 v4.1.1.0 | Microsoft.AspNetCore.Hosting version 1.1.2 | Microsoft Windows 6.1.7601 S | Need help? 的第一行应用第二个映射。您可以在您正在使用的每个构造函数中嵌套映射策略。

myPersonModel

var myPersonModel = function(data) {
  ko.mapping.fromJS(data, contract_mapping, this);
  /* ... */
};
var persons = {
  'value': [{
    "id": "1",
    "civility": "Mr.",
    "firstname": "john",
    "lastname": "doe",
    "phone": "00 00 00 00 00",
    "email": "email@email.com",
    "contract": [{
        "id": "1",
        "gamme": "Gamme 1",
        "formula": "Formula 1"
      },
      {
        "id": "2",
        "gamme": "Gamme 2",
        "formula": "Formula 2"
      }
    ]
  }]
}

var contract_mapping = {
  "contract": {
    create: function(options) {
      return new myContractModel(options.data);
    }
  }
}

var person_mapping = {
  'value': {
    create: function(options) {
      if (options.data != null) {
        return new myPersonModel(options.data);
      }
    }
  }
}

var myContractModel = function(data) {
  ko.mapping.fromJS(data, {}, this);
  this.type = "myContractModel";
};

var myPersonModel = function(data) {
  ko.mapping.fromJS(data, contract_mapping, this);

  this.fullName = ko.computed(function() {
    return this.civility() + ' ' + this.lastname() + ' ' + this.firstname();
  }, this);
}

console.log(
  ko.mapping.fromJS(persons, person_mapping)
    .value()[0]
    .contract().map(x => x.type)
);