gpt4 book ai didi

javascript - 在 Controller 内部使用操作?

转载 作者:行者123 更新时间:2023-12-03 06:28:13 25 4
gpt4 key购买 nike

我是 ember 新手,我想在我的一个操作(分配)中使用单独的操作(显示为随机播放)。我知道我在这里做错了什么,洗牌方法并没有真正做任何事情。我是否错误地调用了它,或者操作不应该被其他操作使用?这是代码:

import Ember from 'ember';

export default Ember.Controller.extend({

taskData: [],
personData: [],
taskIn: ' ',
personIn: ' ',



actions: {

saveTask() {

const task = this.get("taskIn");
this.taskData.push(task);
},

savePerson()
{
const person = this.get("personIn");
this.personData.push(person);
},

print(){
var taskString;

//this.taskData.remove(0);
for(var i = 0; i < this.taskData.length; i++)
{
taskString = taskString + this.taskData[i];
}
alert(taskString);
//alert(this.personData);
},

shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;

// While there remain elements to shuffle...
while (0 !== currentIndex) {

// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;

// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}

return array;
},

//algorithm to match up tasks with people
assign(){


var newTaskD = this.shuffle(this.taskData);
var newPersonD = this.shuffle(this.personData);
var taskString = '';
var peopleString = '';

for(var i = 0; i<newTaskD.length; i++)
{
taskString += " " + newTaskD[i];

}

for(var j = 0; j<peopleString.length; j++)
{
peopleString += " " + newPersonD[j];

}

alert(peopleString);
alert(taskString);

}
}
});

最佳答案

即使您在 actions 哈希中定义操作,它们也会在 Controller 的上下文中被调用。所以 this 是 Controller ,而不是操作哈希。

这就是 this.shuffle 不起作用的原因:因为 shuffle 不是在 Controller 上定义的,而是在 actions 哈希上定义的.

要做的是这样的:

this.actions.shuffle();

但是,shuffle 操作的 this 上下文将是错误的:它将是 actions 哈希,而不是 Controller 。所以你必须重写它:

this.actions.shuffle.call(this);

但这有点丑吧?所以回答你的问题:

or are actions not supposed to be used by other actions?

是的!我建议不要这样做,而是在同一个controller.js文件中调用普通函数或使用 Controller 上定义的普通方法。所以要么这样做:

import Ember from 'ember';

function foo(arg) {
...
return something;
}

export default Ember.Controller.extend({
actions: {
bar() {
let baz = foo(this.things);
...
}
}
}

或者这个:

import Ember from 'ember';

function foo(arg) {
...
return something;
}

export default Ember.Controller.extend({
foo(arg) {
...
return something;
},
actions: {
bar() {
let baz = this.foo(this.things);
...
}
}
}

关于 actions 哈希的想法是将模板调用的函数 (actions) 和普通方法分开。

关于javascript - 在 Controller 内部使用操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38547493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com