如何在knockout中重新绑定相同的viewmodel

时间:2013-02-06 09:17:45

标签: ajax knockout.js

我想用新数据重新绑定相同的模型,或者你可以在调用ajax之后说我想用全新数据更新模型。

function returnData(url,data,type){
    $.post(url, data, function(returnedData) {

    if(type == "search")
    {
    ko.applyBindings(new SearchViewModel(returnedData,"#searchbox",url,data),$("#searchbox")[0]);   
    }
});
}

这是为数据调用ajax的代码,当新数据被重新获取时,它会将其绑定到模型。 第一次不是问题,但下次它会翻倍相同的数据。

returnData(doamin+"/1.0/search",{userid:"12033914132",keyword:""},"search");

我想在输入新的搜索词时调用相同的函数。

我知道我们可以使用observable来更新数据,但我想清除旧的绑定并添加新的

function SearchViewModel(data,id,url,userdata) {
    var self = this;
    // Editable data

    var ParsedData = JSON.parse(data);

    self.Contacts = ko.observableArray(ParsedData.Contacts);
    self.Sms = ko.observableArray(ParsedData.Sms);
    self.Calendar = ko.observableArray(ParsedData.Calendar);
    self.Logs = ko.observableArray(ParsedData.Logs);
    self.Total = ko.toJS(self.Contacts).length+ko.toJS(self.Sms).length+ko.toJS(self.Calendar).length;
    self.ContactsCount = ko.toJS(self.Contacts).length;
    self.SmsCount = ko.toJS(self.Sms).length;
    self.CalendarCount = ko.toJS(self.Calendar).length;
}

2 个答案:

答案 0 :(得分:2)

我只应用绑定一次,然后使用knockout mapping plugin更新现有的视图模型:

function SearchViewModel() {
    var self = this;
    // Editable data

    self.Contacts = ko.observableArray();
    self.Sms = ko.observableArray();
    self.Calendar = ko.observableArray();
    self.Logs = ko.observableArray();
    self.Total = ko.toJS(self.Contacts).length+ko.toJS(self.Sms).length+ko.toJS(self.Calendar).length;
    self.ContactsCount = ko.toJS(self.Contacts).length;
    self.SmsCount = ko.toJS(self.Sms).length;
    self.CalendarCount = ko.toJS(self.Calendar).length;    
}

您需要将计数属性更改为computed observables,但其他所有内容都应由映射插件映射:

var searchViewModel = new SearchViewModel();

function returnData(url,data,type){
    $.post(url, data, function(returnedData) {

    if(type == "search")
    {
      searchViewModel = ko.mapping.fromJS(returnedData);
    }
});
}
ko.applyBindings(new SearchViewModel(returnedData,"#searchbox",url,data),$("#searchbox")[0]);

答案 1 :(得分:0)

您可以将SearchViewModel存储在一个observable中。有了它,您可以更新SearchViewModel而无需任何映射或重新绑定。

function ViewModel() {
    var self = this;

    self.searchViewModel = ko.observable();
}

var viewModel = new ViewModel();
ko.applyBindings(viewModel, $("#searchbox")[0]); 

function returnData(url,data,type){
    $.post(url, data, function(returnedData) {

    if(type == "search")
    {
    // ko.applyBindings(new SearchViewModel(returnedData,"#searchbox",url,data),$("#searchbox")[0]);   
       viewModel.searchViewModel(new SearchViewModel(returnedData,"#searchbox",url,data));
    }
});
}

查看:

<div id="#searchbox" data-bind="if: searchViewModel()">
    <div data-bind="with: searchViewModel()">
       ... your markup
    </div>    
</div>