2016-05-16 44 views
-1
var ViewModel = function() { 
    var self = this; 

    self.defaultValues = { 
     Id: ko.observable(16), 
     name: ko.observable("SUkhi"),   
    }; 
}; 

var model = new ViewModel(); 

ko.applyBindings(model); 

如何通過調用函數來設置默認值16和'Sukhi'。如何在數據庫中設置缺省值

回答

1

有幾種方法可以根據您的需要來做到這一點。

例如1

var ViewModel = function() { 
    var self = this; 
    self.Id = ko.observable(16); 
    self.name: ko.observable("SUkhi") 
}; 

var model = new ViewModel(); 
ko.applyBindings(model); 

// this will create models with the default values 

例2(我的最愛)

var ViewModel = function (ctor) { 
    var self = this; 
    var default: { 
     id = 16 
     name: "SUkhi" 
    } 
    self.Id = ko.observable(); 
    self.name: ko.observable() 

    /// if using pure JS 
    if(!!ctor){ 
     for(var i in ctor){ 
      if(ctor.hasOwnProperty("i") && self.hasOwnProperty("i"){ 
       if(ko.isSubscribable(self[i])) { // check if it is observable 
        self[i](ctor[i]) 
       } 
       else { 
        self[i] = ctor[i]; 
       } 
      } 
     } 
    } 
    // end pure JS 

    /// if using jquery 
    $.extend(self, ctor); 
    // end jquery 
}; 

var model = new ViewModel(); // or 
var model = new ViewModel({ Id: 5, Name: "Whateva"}) 
ko.applyBindings(model); 

從內存中寫的,但它都在那裏

相關問題