[英]Knockback.js: How can I make the view update when backbone save updates the model?
這是我第一次使用Knockback.js 。
我正在研究Knockback的概念驗證,但是當我保存模型時,我很難讓視圖模型更新。 在這種情況下,會發生什么是服務器返回一個設置了id
字段的新Domain
對象,這意味着該對象現在存在於后端。 一旦發生這種情況,我希望UI更改以反映它現在已保存的事實。
這是我正在使用的代碼:
<table cellspacing="0" class="listing-table" id="domainListTable">
<thead>
<tr>
<th scope="col">
Domain
</th>
</tr>
</thead>
<tbody data-bind="foreach: domains">
<tr>
<td>
<!-- ko if:save -->
<a data-bind="attr: { href: domainEditLinkdomainId, title: domain},text : domain">
<span data-bind="text: domain"></span>
</a>
<!-- /ko -->
<!-- ko ifnot:save -->
<input type="text" maxlength="250" style="display:inline-block;" class="medium-text-field" data-bind="value: domain"></input>
<input data-bind="click: save" style="display:inline-block;" type="submit" value="Save New Domain" alt="" title=""/>
<!-- /ko -->
</td>
</tr>
</tbody>
</table>
<br />
<input data-bind="click: addDomain" type="submit" value="Add New Domain" alt="" title=""/>
<script type="text/javascript">
var Domain = Backbone.Model.extend({
defaults: function() {
return {
domain: "New Domain"
};
},
});
var Domains = {};
Domains.Collection = Backbone.Collection.extend({
model: Domain,
url: '/cms/rest/poc/${customerId}/domains/'
});
var domains = new Domains.Collection();
domains.fetch();
var DomainViewModel = kb.ViewModel.extend({
constructor: function(model) {
kb.ViewModel.prototype.constructor.apply(this, arguments);
var self = this;
this.save = kb.observable(model, {
key: 'save',
read: (function() {
return !model.isNew();
}),
write: (function(completed) {
return model.save({}, {
wait: true,
success: function (model, response) {
console.log(model);
console.log(response);
console.log(self);
},
error: function(model, response) {
alert("Oh NooooOOOes you broked it!!!11!")
}
});
})
}, this);
this.domainEditLinkdomainId = ko.dependentObservable(function() {
if(!this.save())
return "";
return "cms?action=domainDetail&domainID=" + this.model().id;
}, this);
}
});
var DomainsViewModel = function(collection) {
this.domains = kb.collectionObservable(collection, { view_model: DomainViewModel });
this.addDomain = function() {
this.domains.push(new DomainViewModel(new Domain()));
};
};
var domainsViewModel = new DomainsViewModel(domains);
ko.applyBindings(domainsViewModel);
</script>
問題似乎是由model.save()
完成的XMLHttpRequest
在讀取save kb.observable
之后才返回,因此html部分不會成功更新,因為它仍然將model.isNew()
視為true。
你可能會看到,我一直在搞亂幾個不同的想法,包括在一個observable上使用valueHasMutated
方法來表明模型已經更新,但我也無法弄清楚如何做到這一點。
任何幫助將不勝感激!
您可以在模型上收聽change:id
事件。
當模型的狀態從新變為持久時,這只會觸發。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.