这是我第一次使用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直到读取保存的kb.observable之后才返回,因此html部分不会成功更新,因为它仍然将model.isNew()视为真。
正如您可能看到的,我一直在考虑一些不同的想法,包括在可观察对象上使用valueHasMutated方法来指示模型已经更新,但我也不知道如何做到这一点。
任何帮助都将不胜感激!
发布于 2013-02-05 04:15:14
您可以在模型上侦听change:id事件。
只有当模型的状态从新变为持久时,才会触发此操作。
https://stackoverflow.com/questions/13185985
复制相似问题