2012-11-07 89 views
1

我是新手去淘汰js,我有一個類似於這個jsfiddle http://jsfiddle.net/daedalus28/vpjhZ/的要求,它很好地從viewmodel渲染json,但我無法做viceversa,因爲從服務器需要json需要呈現相同的視圖。我如何在映射創建函數中映射observablearray?從ViewModel渲染Json和反之亦然

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); 
}) 

;

回答

3

我不確定我是否理解正確,但是您想從ViewModel呈現JSON字符串? 如果是這樣,你必須做這樣的事情:

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

或與mapping plugin