-
-
Save dmaevac/9789880 to your computer and use it in GitHub Desktop.
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
"use strict"; | |
// A function that wraps a given `React.DOM.input`-like component to | |
// apply formatting to the value for display purposes. | |
// | |
// Example: | |
// | |
// var RoundedInput = createFormattedInput(React.DOM.input, { | |
// set: Math.round, | |
// }); | |
var React = require("react"); | |
var isFunction = require("core-util-is").isFunction; | |
var defaults = require("underscore").defaults; | |
var filter = require("object-filter"); | |
var getOnChange = require("react/lib/LinkedValueUtils").getOnChange; | |
function getValue(props) { | |
return props.valueLink ? props.valueLink.value : props.value; | |
} | |
function filterKeys(obj, keys) { | |
return filter(obj, function (val, key) { | |
return keys.indexOf(key) === -1; | |
}); | |
} | |
var ValueFormatter = function (options) { | |
function format(value) { | |
if (options.format) { | |
return options.format.call(this, value); | |
} | |
return value; | |
} | |
function unformat(value) { | |
if (options.unformat) { | |
return options.unformat.call(this, value); | |
} | |
return value; | |
} | |
return { | |
getValueState: function (props) { | |
var value = String(getValue(props)); | |
return { | |
value: format.call(this, value) | |
}; | |
}, | |
componentWillReceiveProps: function (props) { | |
this.setState(this.getValueState(props)); | |
}, | |
handleFormat: function () { | |
var value = unformat.call(this, this.state.value); | |
var e = { target: { value: value } }; | |
getOnChange(this).call(this, e); | |
} | |
}; | |
}; | |
module.exports = React.createClass({ | |
mixins: [ValueFormatter(options)], | |
getInitialState: function () { | |
return this.getValueState(this.props); | |
}, | |
handleChange: function (e) { | |
this.setState({ value: e.target.value }); | |
}, | |
render: function () { | |
var props = defaults({ | |
value: this.state.value, | |
onChange: this.handleChange, | |
onBlur: this.handleFormat | |
}, filterKeys(this.props, ["valueLink"])); | |
return React.DOM.input(props); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment