attrs.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. var Node = require('./node');
  3. /**
  4. * Initialize a `Attrs` node.
  5. *
  6. * @api public
  7. */
  8. var Attrs = module.exports = function Attrs() {
  9. this.attributeNames = [];
  10. this.attrs = [];
  11. this.attributeBlocks = [];
  12. };
  13. // Inherit from `Node`.
  14. Attrs.prototype = Object.create(Node.prototype);
  15. Attrs.prototype.constructor = Attrs;
  16. Attrs.prototype.type = 'Attrs';
  17. /**
  18. * Set attribute `name` to `val`, keep in mind these become
  19. * part of a raw js object literal, so to quote a value you must
  20. * '"quote me"', otherwise or example 'user.name' is literal JavaScript.
  21. *
  22. * @param {String} name
  23. * @param {String} val
  24. * @param {Boolean} escaped
  25. * @return {Tag} for chaining
  26. * @api public
  27. */
  28. Attrs.prototype.setAttribute = function(name, val, escaped){
  29. if (name !== 'class' && this.attributeNames.indexOf(name) !== -1) {
  30. throw new Error('Duplicate attribute "' + name + '" is not allowed.');
  31. }
  32. this.attributeNames.push(name);
  33. this.attrs.push({ name: name, val: val, escaped: escaped });
  34. return this;
  35. };
  36. /**
  37. * Remove attribute `name` when present.
  38. *
  39. * @param {String} name
  40. * @api public
  41. */
  42. Attrs.prototype.removeAttribute = function(name){
  43. var err = new Error('attrs.removeAttribute is deprecated and will be removed in v2.0.0');
  44. console.warn(err.stack);
  45. for (var i = 0, len = this.attrs.length; i < len; ++i) {
  46. if (this.attrs[i] && this.attrs[i].name == name) {
  47. delete this.attrs[i];
  48. }
  49. }
  50. };
  51. /**
  52. * Get attribute value by `name`.
  53. *
  54. * @param {String} name
  55. * @return {String}
  56. * @api public
  57. */
  58. Attrs.prototype.getAttribute = function(name){
  59. var err = new Error('attrs.getAttribute is deprecated and will be removed in v2.0.0');
  60. console.warn(err.stack);
  61. for (var i = 0, len = this.attrs.length; i < len; ++i) {
  62. if (this.attrs[i] && this.attrs[i].name == name) {
  63. return this.attrs[i].val;
  64. }
  65. }
  66. };
  67. Attrs.prototype.addAttributes = function (src) {
  68. this.attributeBlocks.push(src);
  69. };