Created
September 22, 2020 15:24
-
-
Save smailliwcs/d43cefe5620d1300ba3079dd104e973e to your computer and use it in GitHub Desktop.
Knockout extender: filter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ko.extenders.filter = function (target, pattern) { | |
var result = ko.computed({ | |
read: target, | |
write: function (value) { | |
if (typeof value !== "string") { | |
target(value); | |
return; | |
} | |
var current = target(); | |
var filtered = value.replace(pattern, ""); | |
if (filtered !== current) { | |
target(filtered); | |
} else if (value !== current) { | |
target.notifySubscribers(filtered); | |
} | |
} | |
}).extend({ notify: "always" }); | |
result(target()); | |
return result; | |
}; | |
var x = ko.observable().extend({ filter: /[aeiou]/gi }); | |
x("hello"); | |
console.log(x()); | |
x("WORLD"); | |
console.log(x()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
hll | |
WRLD |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment