Почему это пользовательское свойство теряется в обозревателе событий после сериализации? - PullRequest
0 голосов
/ 08 июля 2019

У меня есть прямоугольник A с пользовательским свойством "childs", это свойство является массивом, в который я помещаю ректы B. Прямоугольник B имеет пользовательское свойство "another".

Проблема в том, что послеСериализуя холст и загружая json на холст, слушатель событий не загружает свойство "another" прямоугольника B.

Здесь вы можете лучше увидеть проблему: https://jsfiddle.net/ps7566/y3k5b4c1/

var a = new fabric.Rect({
   left: 70,
   top: 70,
   fill: 'blue',
   width: 100,
   height: 100
});
var b = new fabric.Rect({
   left: 75,
   top: 75,
   fill: 'red',
   width: 50,
   height: 50
});
b.another = 'property';//this custom property is losed in event observer after serialize
a.childs = [];
a.childs.push(b);
canvas.add(a);

canvas.observe("mouse:up",function(e){
if(e.target != null){
   console.log(e.target);
   alert(e.target.childs[0].another);
   //why this is undefined after serialize and load json? 
}
});
function serialize(){
    json = JSON.stringify(canvas.toJSON(['childs','another']));
}
function loadJSON(){
    canvas.loadFromJSON(json);
}

Я хочу, чтобы прослушиватель событий мог получить доступ к свойству "another" даже после загрузки JSON.

1 Ответ

0 голосов
/ 08 июля 2019

Проблема в том, что после загрузки json дочерние объекты не являются объектами класса.Вам нужно переписать toObject и fromObject методы.В методе fromObject вам нужно установить forceAsync в значение false, поскольку вам нужно дождаться создания потомков.

var canvas = new fabric.Canvas("c",{
	width: 600,
  height: 500,
  backgroundColor: 'cyan'
});
var a = new fabric.Rect({
  left: 70,
  top: 70,
  fill: 'blue',
  width: 100,
  height: 100
});
var b = new fabric.Rect({
  left: 75,
  top: 75,
  fill: 'red',
  width: 50,
  height: 50
});
b.another = 'property';//this custom property is losed in event observer after serialize;
a.another = 'property';//this custom property is losed in event observer after serialize;
a.childs = [];
a.childs.push(b);
a.childs.push(b);
canvas.add(a);
//function printObj(){
//	console.log(r);
//}
//function addChild(){
//	r.childs.push(s);
//}
var json;
 serialize = function(){
	json = JSON.stringify(canvas.toJSON(['childs','another']));
}
  loadJSON = function(){
  
  canvas.clear();

	canvas.loadFromJSON(json);
}
canvas.observe("mouse:up",function(e){
	if(e.target != null){
  	console.log(e.target);
    alert(e.target.childs[0].another);//why this is undefined after serialize and load json? 
  }
});
fabric.Rect.prototype.toObject = (function(toObject) {
    return function(propertiesToInclude) {
        var data = toObject.call(this,propertiesToInclude),childs=[];
        
        if(this.childs && this.childs.length){
        	 for(var i= 0 ; i<this.childs.length; i++){
           		childs.push(this.childs[i].toObject(propertiesToInclude));
           }
           
        }
        data.childs = childs;
        return data;
    };
})(fabric.Rect.prototype.toObject);
fabric.Rect.fromObject = function(object, callback, forceAsync) {
 
    var obj = fabric.Object._fromObject('Rect', object, null, false);
    obj.childs = [];
    if(object.childs && object.childs.length){
    	 for(var i= 0 ; i<object.childs.length; i++){
           obj.childs[i] = fabric.Object._fromObject('Rect', object.childs[i], null, 0);
       }
    }
    return callback ? callback(obj) : obj;
  };


//The project has to be programmed in this way. with an array, event o
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.js"></script>
<!-- <button onClick="printObj()">Print rect</button> -->
<!-- <button onClick="addChild()">Add Child</button> -->
<button onClick="serialize()">Serialize</button>
<button onClick="loadJSON()">Load JSON</button>
<!-- <button onClick="canvas.remove(r)">Delete Rect</button>  -->
<canvas id="c"></canvas>
...