Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update directive.js #49

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 35 additions & 23 deletions src/directive.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,47 @@
import {format, setCursor, event} from './utils'
import assign from './assign'
import defaults from './options'
import { format, setCursor } from "./utils"
import assign from "./assign"
import defaults from "./options"

export default function (el, binding) {
if (!binding.value) return
var opt = assign(defaults, binding.value)
export default { bind }

function bind(el, binding, vnode) {
const opt = assign(defaults, binding.value)

let target = el

// v-money used on a component that's not a input
if (el.tagName.toLocaleUpperCase() !== 'INPUT') {
var els = el.getElementsByTagName('input')
if (el.tagName.toLocaleUpperCase() !== "INPUT") {
const els = el.getElementsByTagName("input")
if (els.length !== 1) {
// throw new Error("v-money requires 1 input, found " + els.length)
throw new Error(`v-money requires 1 input, found ${els.length}`)
} else {
el = els[0]
[target] = els
}
}

el.oninput = function () {
var positionFromEnd = el.value.length - el.selectionEnd
el.value = format(el.value, opt)
positionFromEnd = Math.max(positionFromEnd, opt.suffix.length) // right
positionFromEnd = el.value.length - positionFromEnd
positionFromEnd = Math.max(positionFromEnd, opt.prefix.length + 1) // left
setCursor(el, positionFromEnd)
el.dispatchEvent(event('change')) // v-model.lazy
function eventListener(event) {
if (!event.isTrusted) {
return
}
run(target, opt)
target.dispatchEvent(new Event(event.type))
}

el.onfocus = function () {
setCursor(el, el.value.length - opt.suffix.length)
}
target.addEventListener("input", eventListener)
target.addEventListener("change", eventListener)

target.addEventListener("focus", () => {
setCursor(target, target.value.length - opt.suffix.length)
})

target.dispatchEvent(new Event("input")) // force format after initialization
}

el.oninput()
el.dispatchEvent(event('input')) // force format after initialization
function run(target, opt) {
let positionFromEnd = target.value.length - target.selectionEnd
target.value = format(target.value, opt)
positionFromEnd = Math.max(positionFromEnd, opt.suffix.length) // right
positionFromEnd = target.value.length - positionFromEnd
positionFromEnd = Math.max(positionFromEnd, opt.prefix.length + 1) // left
setCursor(target, positionFromEnd)
}