Skip to content

Instantly share code, notes, and snippets.

@robbiespeed
Forked from rwjblue/components.one-way-input.js
Last active March 6, 2017 19:54
Show Gist options
  • Save robbiespeed/7160df23741f6454cf873f3b38410d5a to your computer and use it in GitHub Desktop.
Save robbiespeed/7160df23741f6454cf873f3b38410d5a to your computer and use it in GitHub Desktop.
One Way Input
import Ember from 'ember';
const { get, computed, run, isNone } = Ember;
export default Ember.Component.extend({
tagName: 'input',
attributeBindings: [
'type',
// '_value:value',
],
didInsertElement () {
this.$().val(get(this, '_value'));
},
change({ target }) {
this._processNewValue(target.value);
},
input ({ target }) {
this._processNewValue(target.value);
},
update () {},
_processNewValue (value) {
if (get(this, '_value') !== value) {
this.update(value);
}
run.schedule('afterRender', this, '_syncValue');
},
_syncValue() {
if (this.isDestroyed || this.isDestroying) {
return;
}
let actualValue = get(this, '_value');
let renderedValue = this.readDOMAttr('value');
if (!isNone(actualValue) && !isNone(renderedValue) && actualValue.toString() !== renderedValue.toString()) {
let element = this.$();
let rawElement = element.get(0);
let start;
let end;
// gaurds because only text, search, url, tel and password support this
try {
start = rawElement.selectionStart;
end = rawElement.selectionEnd;
} catch(e) {
// no-op
}
element.val(actualValue);
try {
rawElement.setSelectionRange(start, end);
} catch(e) {
// no-op
}
}
},
_value: computed('positionalParamValue', 'value', {
get () {
let value = get(this, 'positionalParamValue');
if (value === undefined) {
value = get(this, 'value');
}
return value;
}
}),
});
import Ember from 'ember';
const { computed } = Ember;
export default Ember.Controller.extend({
baseVal: 'hello',
val: computed('baseVal', {
get () {
return this.get('baseVal').toUpperCase();
},
set (key, value) {
return value.replace(/\s/g, '').toUpperCase();
}
}),
valB: 'HELLO',
sanitizeValB (value) {
this.set('valB', value.replace(/\s/g, '').toUpperCase());
},
valC: computed('baseVal', {
get () {
return this.get('baseVal').toUpperCase();
},
set (key, value) {
return value.replace(/\s/g, '').toUpperCase();
}
}),
});
<h1>Welcome!</h1>
<p>
{{val}}
<br>
{{one-way-input
value=val
update=(action (mut val))
}}
</p>
<p>
{{valB}}
<br>
{{one-way-input
value=valB
update=(action sanitizeValB)
}}
</p>
<p>
{{valC}}
<br>
{{my-input
value=valC
update=(action (mut valC))
}}
</p>
{{outlet}}
{
"version": "0.4.8",
"dependencies": {
"jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js",
"ember": "2.10.2",
"ember-template-compiler": "2.10.2"
},
"addons": {
"ember-one-way-controls": "2.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment