Created
November 8, 2012 20:33
-
-
Save joeyespo/4041403 to your computer and use it in GitHub Desktop.
Adds a 'trimmed' function to observables for applying trim.
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8" /> | |
<title>Example of Knockout Trimmed Observables</title> | |
<style> | |
h1 { font-size: x-large; } | |
h2 { font-size: large; } | |
p { margin: 32px; } | |
pre { padding: 32px; } | |
label { float: left; width: 100px; } | |
</style> | |
<script src="http://code.jquery.com/jquery-1.8.2.js"></script> | |
<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script> | |
<script src="ko-trimmed-observables.js"></script> | |
<script> | |
$(function() { | |
// An example model, one regular observable, the other calling 'trimmed()' | |
var vm = { | |
regular: ko.observable(' hello! '), | |
trimmed: ko.observable(' hello! ').trimmed() | |
} | |
// Apply bindings | |
ko.applyBindings(vm); | |
}); | |
</script> | |
</head> | |
<body> | |
<h1>Trimmed Observable Example</h1> | |
<p> | |
<label for="regular">Regular:</label> | |
<input name="regular" data-bind="value: regular" /> | |
</p> | |
<p> | |
<label for="trimmed">Trimmed:</label> | |
<input name="trimmed" data-bind="value: trimmed" /> | |
</p> | |
<h2>Values</h2> | |
<pre> | |
regular = '<span data-bind="text: regular"></span>' | |
trimmed = '<span data-bind="text: trimmed"></span>' | |
</pre> | |
</body> | |
</html> |
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
// Trimmed Observables | |
// Adds the 'trimmed' function | |
ko.subscribable.fn.trimmed = function() { | |
return ko.computed({ | |
read: function() { | |
return this().trim(); | |
}, | |
write: function(value) { | |
this(value.trim()); | |
this.valueHasMutated(); | |
}, | |
owner: this | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment