从函数返回值时遇到问题

时间:2015-02-24 07:37:18

标签: javascript function oop events

您好我在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),它的工作原理。我试图从选择框中取出值,这样我就可以将值与事件分开,这样我就可以使用代码other parts in my code in this jsfiddle的其他部分中的值。在此先感谢您的帮助。

编辑我希望能够在更改事件的某个地方使用金额。因此,如果用户点击3我希望能够拥有该值,那么我可以执行与更改事件无关的另一个功能,即使该值在用户输入时更改。发布/订阅?

3 个答案:

答案 0 :(得分:0)

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

$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;
            }
        })

你可以在参数中看到你想要的变量[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'));

答案 1 :(得分:0)

您所返回的返回仅退出事件的功能,但不退出AmountToDisplay函数。

  1. 事件必须在函数
  2. 之外
  3. 该函数只需要返回带有amountItems
  4. 的select值
  5. console.log或您的逻辑必须在事件中
  6. http://jsfiddle.net/mdf083Lb/2/

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

答案 2 :(得分:0)

您不需要定义事件方法或其他内容,您可以使用jquery选择器在任意位置获取选择框的选定值:

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