在带有 interactJS 的结束回调函数中使用可注入服务
using the injectable service in end callback function with interactJS
我将 interactJS 与 angular 结合使用,使用户可以使用 class 'draggable' 执行元素的拖放操作。一切正常,直到我需要在结束拖动的回调函数中使用组件的注入服务。这是我试过的:
ngOnInit() {
interact('.draggable')
.draggable({
inertia: true,
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
autoScroll: true,
listeners: { move: this.dragMoveListener, end: this.stackForUndo }
})
}
stackForUndo() {
// get current state of svg
let current_state = document.getElementById("Logo").outerHTML;
// clear redo stack
this.menuService.redo = {}
// get the previous saved actions
let actions = { elements: [] };
// if no action has been cached, initialise the localStorage undo element
if (actions == undefined) {
actions = { elements: [] };
// save stringified empty action to localStorage
this.menuService.undo = actions;
}
// add the current state of the svg
if(actions.elements.length >= 5){
actions.elements.shift();
}
actions.elements.push(current_state);
this.menuService.undo = actions;
}
拖动后我无法放下元素并在浏览器控制台中收到以下错误
Cannot read property menuService of undefined (in this.menuService.redo = {})
你的问题的根源是 stackForUndo
丢失了上下文,为了解决这个问题,我只将它绑定到组件如下:
ngOnInit() {
interact('.draggable')
.draggable({
inertia: true,
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
autoScroll: true,
listeners: { move: this.dragMoveListener, end: this.stackForUndo.bind(this) }
})
}
我将 interactJS 与 angular 结合使用,使用户可以使用 class 'draggable' 执行元素的拖放操作。一切正常,直到我需要在结束拖动的回调函数中使用组件的注入服务。这是我试过的:
ngOnInit() {
interact('.draggable')
.draggable({
inertia: true,
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
autoScroll: true,
listeners: { move: this.dragMoveListener, end: this.stackForUndo }
})
}
stackForUndo() {
// get current state of svg
let current_state = document.getElementById("Logo").outerHTML;
// clear redo stack
this.menuService.redo = {}
// get the previous saved actions
let actions = { elements: [] };
// if no action has been cached, initialise the localStorage undo element
if (actions == undefined) {
actions = { elements: [] };
// save stringified empty action to localStorage
this.menuService.undo = actions;
}
// add the current state of the svg
if(actions.elements.length >= 5){
actions.elements.shift();
}
actions.elements.push(current_state);
this.menuService.undo = actions;
}
拖动后我无法放下元素并在浏览器控制台中收到以下错误
Cannot read property menuService of undefined (in this.menuService.redo = {})
你的问题的根源是 stackForUndo
丢失了上下文,为了解决这个问题,我只将它绑定到组件如下:
ngOnInit() {
interact('.draggable')
.draggable({
inertia: true,
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
autoScroll: true,
listeners: { move: this.dragMoveListener, end: this.stackForUndo.bind(this) }
})
}