2

Type checking in Vue requires the constructor function to be passed in as the type:

props: {
  coords: {
    type: Coordinates,
    required: true,
  },
},

I can't work out how to find the Coordinates constructor. Can't use Object because it doesn't inherit from anything, and would prefer not to just allow anything.

There's nothing on MDN about how to access it directly: https://developer.mozilla.org/en-US/docs/Web/API/Coordinates

Any ideas?

EDIT: To clarify, window.Coordinates is undefined. The above code example doesn't work.

callumacrae
  • 8,185
  • 8
  • 32
  • 49

3 Answers3

2

Coordinates is not something exposed in the browser to be used by web developers. It's an interface defined by W3C geo specs, for browser vendors who implement the geolocation features. An interface describes how a certain type of data structure looks like. For example, coords in the following example:

navigator.geolocation.getCurrentPosition(function (pos) {
  var coords = pos.coords
  console.log(coords)
})

Even though you could retrieve the literal of Coordinates with following code. It's just an object (yes, it's prototype, not constructor), you can barely do anything.

Object.getPrototypeOf(pos.coords)

So two points here:

  1. Coordinates is not for web developers.
  2. Coordinates is not even a function.

The only way I guess, is to define your own validator and check whether the input value meets your requirement. This would be easier because Coordinates has a special toString() symbol:

props: {
  coords: {
    validator: function (value) {
      return value.toString() === '[object Coordinates]'
    }
  }
}

However, this validator may fail if you hand-craft your own coords data. A more generic way is like duck-typing, just check whether it has proper properties you need, latitude and longitude usually.

tony19
  • 125,647
  • 18
  • 229
  • 307
Leo
  • 13,428
  • 5
  • 43
  • 61
0

You will need to check if the value is an intance of your contructor, using a custom validator:

coords {
  validator: function (value) {
      return value instanceOf Coordinates; // Coordinates is a constructor in your case
  }
}

Take a look of HTML5 Geolocation Documentation.

Med
  • 2,772
  • 1
  • 11
  • 14
0

I am dealing with this problem too. My solution is define a fake constructor:

function Coordinates () {}
Coordinates.prototype = Object.prototype

in vue component

props: {
  coords: {
    type: Coordinates
  }
}

This will work because Vue use instanceof to validate custom types.

  • This defeats the point in using the validation: you might as well use `type: Object`. – callumacrae Jan 23 '17 at 09:50
  • @callumacrae : Vue validate `type: Object` using `Object.prototype.toString.call(propValue) === '[object Object]'`,so you can NOT use `type: Object` to validate any object with constructor – Zhang Visper Feb 09 '17 at 04:02