Javascript函数逻辑

时间:2013-12-06 09:44:09

标签: javascript ember.js

想要朋友的代码帮助。我们正在共同努力,但我对JavaScript相对较新。我已经包含了下面的代码,并希望了解逻辑。我在很大程度上理解它,但没有全面了解。

App.SummaryController = Ember.ObjectController.extend({
    userExpense: function() {

        var userExpenseMap = {}
        var expenses = this.get('controllers.expenses');
        expenses.forEach(function(expense){
            if(userExpenseMap[expense.get('whoPaid')]){
                userExpenseMap[expense.get('whoPaid')] += expense.get('amount');
            }
            else{
                userExpenseMap[expense.get('whoPaid')] = expense.get('amount');   
            }
        });
        userExpenseList = []
        for(var key in userExpenseMap){
            var obj = {};
            obj.name = key;
            obj.expense = userExpenseMap[key];
            userExpenseList.push(obj);
        }
        console.log(userExpenseList);
        return userExpenseList;
    }.property('controllers.expenses.@each.amount')  

});

1 个答案:

答案 0 :(得分:1)

我会解释这个功能,但如果你想要它的余烬部分打开一周的课程。

userExpense: function() {
    // create an object (hash)
    var userExpenseMap = {}
    // in ember, grab the expenses controller, this shouldn't work, because in order to
    // access another controller he should have a needs: ['expenses'] in this controllers hash
    var expenses = this.get('controllers.expenses');
    //iterate over each expense, named expense in the iteration
    expenses.forEach(function(expense){
        // if the object hash contains the whoPaid already, increment it by this amount
        if(userExpenseMap[expense.get('whoPaid')]){
            userExpenseMap[expense.get('whoPaid')] += expense.get('amount');
        }
        // otherwise create a new person who paid (as the key and set the amount)
        else{
            userExpenseMap[expense.get('whoPaid')] = expense.get('amount');   
        }
    });
    // create a global list (bad practice)
    userExpenseList = []
    // iterate through all the property names (keys) in the object hash
    for(var key in userExpenseMap){
        // set obj to a new object/hash (obj is actually hoisted out of here
        // so this isn't creating a new variable, just setting obj each time
        var obj = {};
        //set two properties on it, name and expense with the values from above
        obj.name = key;
        obj.expense = userExpenseMap[key];
        // put it into the global list
        userExpenseList.push(obj);
    }
    // print it out
    console.log(userExpenseList);
    // return it
    return userExpenseList;
}.property('controllers.expenses.@each.amount')  

这是ember中的一个计算属性,这就是最后property函数的内容,而内部的部分是依赖关系,所以任何时候任何一个费用实例的数量都存在于费用控制器(这是一个数组)更改属性将被标记为脏(所以如果有人观察它,或依赖它,他们将更新。依赖更新等是Ember Magic,不是真正的Javascript相关)