简体   繁体   English

使用JSON处理时,剔除计算对象不起作用

[英]knockout computed object not working when working with JSON

I am new to Knockout, The problem is that I try to load object from JSON and also use computed value please see jsfiddle example and tell me what I am doing wrong it should display "Hello World" + "start date" (in the third line) http://jsfiddle.net/qp86wbdt/3/ 我是Knockout的新手,问题是我尝试从JSON加载对象并也使用计算值,请参见jsfiddle示例,并告诉我我做错了什么,它应该显示“ Hello World” +“开始日期”(在第三篇中)行) http://jsfiddle.net/qp86wbdt/3/

self.starttextt= ko.computed(function() {
    return  " Hello world " + this.start();
}, this);             

it may worth mentioning that this computed object lives in "events" object (which is loaded from json) while "events" object live in the ViewModel object. 值得一提的是,此计算对象位于“事件”对象(从json加载)中,而“事件”对象则位于ViewModel对象中。

Appreciate your help, thanks 感谢您的帮助,谢谢

You have quite some problems with your current approach: 您目前的方法存在很多问题:

You need to fix your Event function to take some parameter to fill in with data: 您需要修复Event函数以采用一些参数来填充数据:

 function Event(data) {
     var self = this;
     self.title = ko.observable(data.title);
     self.start = ko.observable(data.start);
     self.starttextt = ko.computed(function () {
         return " Hello world " + this.start();
     }, this);
 }

Then writing var data = [Event]; 然后写入var data = [Event]; just create an array with the Event function and it does not do any kind of mapping. 只需使用Event函数创建一个数组,它就不会进行任何类型的映射。 You need to call map on your objs array: 您需要在objs数组上调用map

 var objs = JSON.parse(js);
 var data = objs.map(function (e) {
     return new Event(e)
 });

And you need to use data in your viewModel instead of obj 而且您需要在viewModel中使用data而不是obj

 var viewModel = function () {
     var self = this;
     self.events = ko.observableArray(data);
 };

Demo JSFiddle . 演示JSFiddle

However you don't need to write all these mapping code because there is already a plugin exists called Mapping plugin which is built to handle these kind of situations. 但是,您无需编写所有这些映射代码,因为已经存在一个名为Mapping插件的插件 ,该插件旨在处理此类情况。

Here is your sample rewritten with the mapping plugin: 这是使用映射插件重写的示例:

 var mapping = {
     create: function (options) {
         var event = ko.mapping.fromJS(options.data);
         event.starttextt = ko.computed(function () {
             return " Hello world " + event.start();
         }, event);
         return event;
     }
 }
 var viewModel = function () {
     var self = this;
     self.events = ko.mapping.fromJSON(js, mapping);
 };

Demo JSFiddle . 演示JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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