从函数返回值时遇到问题

having problems returning value from functions

你好我在从 AmountToDisplay() 函数返回值时遇到问题我觉得模块方法是合适的但是因为我是 OOP 的新手所以我在设置它时遇到了问题

function AmountToDisplay(){
    $emitter = $({});
    $('#amountItems').change(function(){
        var amountchosen = $("#amountItems option:selected").val();
        $emitter.trigger('amountUpdate', amountchosen);
    });

    $emitter.on('amountUpdate', function(e, val){
        if(val == 2){
            return 2;
        }else if(val == 3){
            return 3;
        }else if(val == 4){
            return 4;
        }
    })
}

我希望能够做类似

的事情
if(AmountToDisplay() ==2){
    ..append 2 items to body
}else if(AmountToDisplay() ==3){
    ..append 3 items to body
}

console.log(AmountToDisplay()) 给出未定义

我没有返回,而是使用警报方法 alert(2),它有效。我试图从 select 框中获取值,这样我就可以将值与事件分离,这样我就可以在我的代码 other parts in my code in this jsfiddle 的其他部分使用该值。预先感谢您的帮助。

编辑 事情是我希望能够在更改事件之外的某个地方使用金额。因此,如果用户单击 3,我希望能够拥有该值,这样即使用户输入时值发生变化,我也可以执行与更改事件无关的另一个功能。 pub/sub?

尝试通过后门。使用参数来欺骗你想要的变量。

$emitter.on('amountUpdate', function(e, val){
            console.log(arguments);
            if(val == 2){
                return 2;
            }else if(val == 3){
                return 3;
            }else if(val == 4){
                return 4;
            }
        })

你可以看到你想要的变量在arguments[1]中 在这里返回任何东西也不起作用。它实际上什么都不做。

您需要将其传递给事件处理程序。

所以像这样修改你的代码:

 $emitter.on('amountUpdate', function(e, val){
        val = arguments[1];
        if(val == 2){
            myEventHandlerfor2(val,e);
        }else if(val == 3){
            myEventHandlerfor3(val,e);
        }else if(val == 4){
            myEventHandlerfor4(val,e);
        }
    })

编辑以显示如何将其放入对象

function FruitBasket() {
    this.apples = 0;
    this.pears = 0;
    this.bananas = 0;
    this.iwonteatthat = 0;
}
FruitBasket.prototype.addFruit = function(which) {
    switch(which) {
        case 0 : this.apples++;break;
        case 1 : this.pears++;break;
        case 2 : this.bananas++;break;
        case 0 : this.iwonteathat++;break;
    }
}
FruitBasket.prototype.registerManipulator = function(manipulator) {
    if(!(manipulator instanceof jQuery)) {
        manipulator = $(manipulator);
    }
    manipulator.on('amountUpdate', jQuery.proxy(function(e, val){
        val = arguments[1];
        this.addFruit(val);
    },this);

}

myFruitBasket = new FruitBasket();
myFruitBasket.registerManipulator($('#formfieldstuff'));
myFruitBasket.registerManipulator(document.getElementById('OtherManipulator'));

你有的return只退出了事件的功能,没有退出AmountToDisplay的功能。

  1. 事件必须在函数之外
  2. 函数只需要return的值select和amountItems
  3. console.log 或您的逻辑必须在事件中

http://jsfiddle.net/mdf083Lb/2/

function AmountToDisplay(){
    return $("#amountItems option:selected").val();
}
$("select").change(function(){
    console.log(AmountToDisplay());
});

您不需要定义事件方法或其他东西,您可以通过使用 jquery [=14] 在任何您想要的地方获得 select 框的 selected 值=]或:

var amountToDisplay = $("#amountItems option:selected").val();