Skip to content

Instantly share code, notes, and snippets.

@joeyespo
Created November 8, 2012 20:33
Show Gist options
  • Save joeyespo/4041403 to your computer and use it in GitHub Desktop.
Save joeyespo/4041403 to your computer and use it in GitHub Desktop.
Adds a 'trimmed' function to observables for applying trim.
<!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>
// 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