2013-09-26 68 views
1

我想使用映射插件與淘汰賽視圖模型:最好的方式來實現視圖模型與映射(採用淘汰賽)

var TasksListViewModel = (function() { 
    var self = this; 
    var GET_PATH = "/Tasks/Index"; 

    self.loadData = function() { 
     $.getJSON(GET_PATH, function (data) { 
      ko.mapping.fromJS(data, {}, self); 
      setSubscribers(); 
      setComputed(); 
      ko.applyBindings(self);    
     }); 
    }; 

    self.updateData = function() { 
     $.getJSON(GET_PATH, 
      { 
       page: self.Page()     
      }, function (data) { 
      ko.mapping.fromJS(data, TasksListViewModel); 
     }); 
    }; 

    self.setSubscribers = function() { 
     self.Page.subscribe(function (newPage) {    
      self.updateData(); 
     });  
    }; 

    self.setComputed = function() { 
     self.TotalPages = ko.computed(function() { 
      return Math.ceil(self.Total()/self.PageSize()); 
     });   
    } 

    return self; 
}()); 

但唯一的映射後,我可以宣佈用戶&計算觀測。這是正確的方式嗎?

+0

找到如何避免setComputed功能,只需要添加兩個額外的參數爲每個ko.computed - self&{deferEvaluation:true} – user2820602

回答

0

我個人很喜歡這種方法

ViewModel = function(data) { 
    var mapping = { 
     myArray: { 
      create: function(options) { 
       return new ChildViewModel(options.data); 
      } 
     } 
    }; 

    ko.mapping.fromJS(data, mapping, this); 

    this.computed = ko.computed(this.getComputed, this); 
}; 

ViewModel.prototype = { 
    getComputed: function() { 
     return this.myData() + "computed"; 
    } 
}; 

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

http://jsfiddle.net/QEKyP/1

當更新您只需撥打ko.mapping.fromJS(data, mapping, this)再次