http://jsfiddle.net/neonms92/xybGG/ 扩展程序: ko.extenders.withPrevious = function (target) { // Define new properties for previous value and whether it's changed target.previous = ko.observable(); target.changed = ko.computed(function () { return target() !== target.previous(); }); // Subscribe to observable to update previous, before change. target.subscribe(function (v) { target.previous(v); }, null, 'beforeChange'); // Return modified observable return target;} 用法示例: // Define observable using 'withPrevious' extensionself.hours = ko.observable().extend({ withPrevious: 1 });// Subscribe to observable like normalself.hours.subscribe(function () { if (!self.hours.changed()) return; // Cancel if value hasn't changed print('Hours changed from ' + self.hours.previous() + ' to ' + self.hours());});jsfiddle link: http://jsfiddle.net/T8ee7/When I call Knockout's subscribe method is there a way I can get both the previous and new value? Right now, I can only call get these values separately.I want to trigger some code if the old and new value are different.I suppose I could do the following, but it can get messy...(http://jsfiddle.net/MV3fN/)var sv = sv || {};sv.PagedRequest = function (pageNumber, pageSize) { this.pageNumber = ko.observable(pageNumber || 1); this.numberOfPages = ko.observable(1); this.pageSize = ko.observable(pageSize || sv.DefaultPageSize);};var _pagedRequest = new sv.PagedRequest();var oldValue;_pagedRequest.pageNumber.subscribe(function (previousValue) { console.log("old: " + previousValue); oldValue = previousValue;}, _pagedRequest, "beforeChange");_pagedRequest.pageNumber.subscribe(function (newValue) { console.log("new: " + newValue); if (oldValue != newValue) { console.log("value changed!"); }});_pagedRequest.pageNumber(10);_pagedRequest.pageNumber(20); 解决方案 I prefer using an observable extender.http://jsfiddle.net/neonms92/xybGG/Extender:ko.extenders.withPrevious = function (target) { // Define new properties for previous value and whether it's changed target.previous = ko.observable(); target.changed = ko.computed(function () { return target() !== target.previous(); }); // Subscribe to observable to update previous, before change. target.subscribe(function (v) { target.previous(v); }, null, 'beforeChange'); // Return modified observable return target;}Example Usage:// Define observable using 'withPrevious' extensionself.hours = ko.observable().extend({ withPrevious: 1 });// Subscribe to observable like normalself.hours.subscribe(function () { if (!self.hours.changed()) return; // Cancel if value hasn't changed print('Hours changed from ' + self.hours.previous() + ' to ' + self.hours());}); 这篇关于淘汰赛2.2.0,在更改之前订阅获取值和新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-31 22:13