new node.findAncestors(selector) and node.findAncestor(selector) functions. close #116

This commit is contained in:
Anton Lavrenov
2015-12-25 21:35:19 +07:00
parent c79fcd377e
commit 28e8758d29
5 changed files with 148 additions and 26 deletions

View File

@@ -533,7 +533,7 @@
_delegate: function(event, selector, handler) {
var stopNode = this;
this.on(event, function(evt) {
var targets = evt.target._findMatchers(selector, stopNode);
var targets = evt.target.findAncestors(selector, true, stopNode);
for(var i = 0; i < targets.length; i++) {
evt = Konva.Util.cloneObject(evt);
evt.currentTarget = targets[i];
@@ -1195,22 +1195,56 @@
getParent: function() {
return this.parent;
},
_findMatchers: function(selector, stopNode) {
/**
* get all ancestros (parent then parent of the parent, etc) of the node
* @method
* @memberof Konva.Node.prototype
* @param {String} [selector] selector for search
* @param {Boolean} [includeSelf] show we think that node is ancestro itself?
* @param {Konva.Node} [stopNode] optional node where we need to stop searching (one of ancestors)
* @returns {Array} [ancestors]
* @example
* // get one of the parent group
* var parentGroups = node.findAncestors('Group');
*/
findAncestors: function(selector, includeSelf, stopNode) {
var res = [];
if (this._isMatch(selector)) {
if (includeSelf && this._isMatch(selector)) {
res.push(this);
}
var parent = this.parent;
if (!parent) {
return res;
var ancestor = this.parent;
while(ancestor) {
if (ancestor === stopNode) {
return res;
}
if (ancestor._isMatch(selector)) {
res.push(ancestor);
}
ancestor = ancestor.parent;
}
if (parent === stopNode) {
return res;
}
return res.concat(parent._findMatchers(selector, stopNode));
return res;
},
/**
* get ancestor (parent or parent of the parent, etc) of the node that match passed selector
* @method
* @memberof Konva.Node.prototype
* @param {String} [selector] selector for search
* @param {Boolean} [includeSelf] show we think that node is ancestro itself?
* @param {Konva.Node} [stopNode] optional node where we need to stop searching (one of ancestors)
* @returns {Konva.Node} ancestor
* @example
* // get one of the parent group
* var group = node.findAncestors('.mygroup');
*/
findAncestor: function(selector, includeSelf, stopNode) {
return this.findAncestors(selector, includeSelf, stopNode)[0];
},
// is current node match passed selector?
_isMatch: function(selector) {
if (!selector) {
return false;
}
var selectorArr = selector.replace(/ /g, '').split(','),
len = selectorArr.length,
n, sel;