【发布时间】:2012-10-22 13:35:31
【问题描述】:
这是我第一次与Knockback.js 合作。
我正在研究 Knockback 概念证明,但我很难在保存模型时更新视图模型。在这种情况下,服务器会返回一个新的 Domain 对象,其中设置了 id 字段,这意味着该对象现在存在于后端。一旦发生这种情况,我希望 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() 为真.
正如您可能看到的那样,我一直在搞砸一些不同的想法,包括在 observable 上使用 valueHasMutated 方法来指示模型已更新,但我不知道如何也这样做。
任何帮助将不胜感激!
【问题讨论】:
-
如果您将内容保存到模型中,模型应根据其状态触发不同的事件。来自 Backbone 文档:
Calling save with new attributes will cause a "change" event immediately, a "request" event as the Ajax request begins to go to the server, and a "sync" event after the server has acknowledged the successful change. Pass {wait: true} if you'd like to wait for the server before setting the new attributes on the model.你不能让你的观点之一听听这个事件吗?
标签: javascript backbone.js knockout.js knockback.js