Knockout simplify Object.setPrototypeOf

This commit is contained in:
the-djmaze 2023-03-06 11:05:44 +01:00
parent b7963ebfa0
commit 4dbcade830
5 changed files with 42 additions and 60 deletions

View file

@ -29,9 +29,7 @@ ko.observable = initialValue => {
ko.subscribable['fn'].init(observable);
// Inherit from 'observable'
Object.setPrototypeOf(observable, observableFn);
return observable;
return Object.setPrototypeOf(observable, observableFn);
}
// Define prototype for observables

View file

@ -4,12 +4,12 @@ ko.observableArray = initialValues => {
if (typeof initialValues != 'object' || !('length' in initialValues))
throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
var result = ko.observable(initialValues);
Object.setPrototypeOf(result, ko.observableArray['fn']);
return result.extend({'trackArrayChanges':true});
return Object.setPrototypeOf(ko.observable(initialValues), ko.observableArray['fn']).extend({'trackArrayChanges':true});
};
ko.observableArray['fn'] = {
// Note that for browsers that don't support proto assignment, the
// inheritance chain is created manually in the ko.observableArray constructor
ko.observableArray['fn'] = Object.setPrototypeOf({
'remove': function (valueOrPredicate) {
var underlyingArray = this.peek();
var removed = false;
@ -29,11 +29,7 @@ ko.observableArray['fn'] = {
}
removed && this.valueHasMutated();
}
};
// Note that for browsers that don't support proto assignment, the
// inheritance chain is created manually in the ko.observableArray constructor
Object.setPrototypeOf(ko.observableArray['fn'], ko.observable['fn']);
}, ko.observable['fn']);
// Populate ko.observableArray.fn with native arrays functions
Object.getOwnPropertyNames(Array.prototype).forEach(methodName => {

View file

@ -187,10 +187,7 @@ ko.exportProperty(ko_subscribable_fn, 'extend', ko_subscribable_fn.extend);
// For browsers that support proto assignment, we overwrite the prototype of each
// observable instance. Since observables are functions, we need Function.prototype
// to still be in the prototype chain.
Object.setPrototypeOf(ko_subscribable_fn, Function.prototype);
ko.subscribable['fn'] = ko_subscribable_fn;
ko.subscribable['fn'] = Object.setPrototypeOf(ko_subscribable_fn, Function.prototype);
ko.isSubscribable = instance =>
typeof instance?.subscribe == "function" && typeof instance.notifySubscribers == "function";