Aucune description

binds.js 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { attributesOnly, directives } from "./directives"
  2. let binds = {}
  3. export function bind(name, bindings) {
  4. let getBindings = typeof bindings !== 'function' ? () => bindings : bindings
  5. if (name instanceof Element) {
  6. return applyBindingsObject(name, getBindings())
  7. } else {
  8. binds[name] = getBindings
  9. }
  10. return () => {} // Null cleanup...
  11. }
  12. export function injectBindingProviders(obj) {
  13. Object.entries(binds).forEach(([name, callback]) => {
  14. Object.defineProperty(obj, name, {
  15. get() {
  16. return (...args) => {
  17. return callback(...args)
  18. }
  19. }
  20. })
  21. })
  22. return obj
  23. }
  24. export function addVirtualBindings(el, bindings) {
  25. let getBindings = typeof bindings !== 'function' ? () => bindings : bindings
  26. el._x_virtualDirectives = getBindings()
  27. }
  28. export function applyBindingsObject(el, obj, original) {
  29. let cleanupRunners = []
  30. while (cleanupRunners.length) cleanupRunners.pop()()
  31. let attributes = Object.entries(obj).map(([name, value]) => ({ name, value }))
  32. let staticAttributes = attributesOnly(attributes)
  33. // Handle binding normal HTML attributes (non-Alpine directives).
  34. attributes = attributes.map(attribute => {
  35. if (staticAttributes.find(attr => attr.name === attribute.name)) {
  36. return {
  37. name: `x-bind:${attribute.name}`,
  38. value: `"${attribute.value}"`,
  39. }
  40. }
  41. return attribute
  42. })
  43. directives(el, attributes, original).map(handle => {
  44. cleanupRunners.push(handle.runCleanups)
  45. handle()
  46. })
  47. return () => {
  48. while (cleanupRunners.length) cleanupRunners.pop()()
  49. }
  50. }