从ViewModel渲染Json,反之亦然

时间:2012-11-07 19:10:54

标签: knockout.js knockout-mapping-plugin

我是淘汰js的新手,我有一个类似于这个jsfiddle http://jsfiddle.net/daedalus28/vpjhZ/的要求,它非常适合从viewmodel渲染json,但我无法做反之亦然,因为服务器的json需要渲染相同的观点。我如何在映射创建函数中映射observablearray?

var FilterGroup = function(parent) {

    this.join = ko.observable('All');
    this.filters = ko.observableArray([new Filter(this)]);

    this.addFilter = function() {
        var filter = new Filter(this);
        this.filters.push(filter);
        this.filters.valueHasMutated();
    };
    this.addGroup = function() {
        var group = new FilterGroup(this);
        this.filters.push(group);
        this.filters.valueHasMutated();
    };
    this.remove = (function(parent) {
        return function() {
            parent.filters.remove(this);
        }
    })(parent);

     this.isRoot = (function(parent) { 
        return function() {
            return parent ? false : true;
        }
    })(parent);


    var mappingOptions = {
        filters: {
            create: function(args) {
                   return new function () {

                   filters = ko.observableArray([new Filter(args.data)]);

      };

            }
        }
    };

    ko.mapping.fromJS(parent, mappingOptions, this);


};

var data = {filters:{join:'All',filters:[{field:{name:'IsDeleted',label:'Deleted'},modifier:'contains',criteria:'50'},{join:'All',filters:[{field:{name:'IsDeleted',label:'Deleted'},modifier:'equals',criteria:'20'}]},{field:{name:'Email',label:'Email'},modifier:'equals',criteria:'30'}]}};

var viewModel = {
    filters: new FilterGroup(data.filters),
    options:  {
        joins: ['All', 'Any'],
        modifiers: [
            'equals',
            'not equal to',
            'less than',
            'greater than',
            'contains',
            'does not contain',
            'starts with'
        ],
        fields: [{"name":"Id","label":"ContactID"},{"name":"IsDeleted","label":"Deleted"}],
    },

    toJSON: function() {
        return {
             filters: this.filters
        }
    }
  };


$(function() {


    ko.applyBindings(viewModel);
})

1 个答案:

答案 0 :(得分:3)

我不确定我是否理解正确,但您想从ViewModel渲染JSON字符串? 如果是这样,你将不得不这样做:

var result = JSON.stringify(unwrapObservable(myViewModel));

或使用mapping plugin