Search code examples
javascriptjointjs

JointJs initializing custom element


I have the following custom element:

var ir = joint.dia.Element.define('my.Rectangle', {
  attrs: {
    body: {
      // ...
    },
    header: {
      // ...
    }
  }
}, {
  initialize: function() {
    this.on("change:header", function() {
                console.log('header change')
            }, this), joint.dia.Element.prototype.initialize.apply(this, arguments)
  },
  markup: [{
      tagName: 'rect',
      selector: 'body',
  }, {
      tagName: 'text',
      selector: 'header'
  }]
});

I want to break the header's text with joint.util.breakText and set the body's size, to fit in it, every time it changes. (Even first time it set)

After

var rect = new joint.shapes.my.Rectangle()
rect.attr('header/text', 'FooBarBaz')
rect.addTo(graph);

nothing happens, the shape is added to the screen, but nothing in the console log.


Solution

  • change:header will listen to changes in the header property. To listen to this, use rect.prop instead of rect.attr:

    rect.prop('header', 'FooBarBaz')
    

    From the docs, at http://resources.jointjs.com/docs/jointjs/v2.2/joint.html#dia.Element.prototype.prop:

    This is an equivalent of the attr() method but this time for custom data properties.

    To listen to attribute changes, use change:attrs:

    this.on('change:header', function (element, opt) {
      if (opt.propertyPath === 'attrs/header/text') {
        console.log('header change');
      }
    }, this), joint.dia.Element.prototype.initialize.apply(this, arguments);