2014-12-07 82 views
1

我的模板助手有重複的代碼:如何幹掉流星中的模板助手?

Template.foodMenu.helpers({ 
    breakfast: function() { 
    var breakfastItems = EatingTimes.find(// query for breakfast items); 
    // function to sort breakfastItems in here (code duplication) 
    }, 
    lunch: function() { 
    var lunchItems = EatingTimes.find(// query for lunch items); 
    // function to sort lunchItems in here (code duplication) 
    }, 
    dinner: function() { 
    var dinnerItems = EatingTimes.find(// query for dinner items); 
    // function to sort breakfastItems in here (code duplication) 
    } 
); 

我想擦乾了起來:

Template.foodMenu.helpers({ 
    breakfast: function() { 
    var breakfastItems = EatingTimes.find(// query for breakfast items); 
    sortFoodItems(breakfastItems); 
    }, 
    lunch: function() { 
    var lunchItems = EatingTimes.find(// query for lunch items); 
    sortFoodItems(lunchItems); 
    }, 
    dinner: function() { 
    var dinnerItems = EatingTimes.find(// query for dinner items); 
    sortFoodItems(dinnerItems); 
    } 
); 

我在哪裏可以把這個功能讓我可以幹起來?如何命名空間以便我可以正確調用它?如果這有所作爲,我正在使用Iron Router。

var sortFoodItems = function (foodItems) { 
    // code to sort out and return foodItems to particular method that calls it 
}; 
+1

只需將它放在同一個文件中(在頂層)爲你的助手? – 2014-12-07 19:26:59

回答

1

只要定義如果你想使用sortFoodItems在多個文件的功能,創建名爲lib文件夾,把文件functions.js功能,你在同一個文件

var sortFoodItems = function (foodItems) { 
    // code to sort out and return foodItems to particular method that calls it 
}; 

Template.foodMenu.helpers({ 
    breakfast: function() { 
    var breakfastItems = EatingTimes.find(/* query for breakfast items */); 
    sortFoodItems(breakfastItems); 
    }, 
    lunch: function() { 
    var lunchItems = EatingTimes.find(/* query for lunch items */); 
    sortFoodItems(lunchItems); 
    }, 
    dinner: function() { 
    var dinnerItems = EatingTimes.find(/* query for dinner items */); 
    sortFoodItems(dinnerItems); 
    } 
}); 

助手功能之前無var關鍵字使其成爲全局。例如:

//lib/functions.js 
sortFoodItems = function (foodItems) { 
    // code to sort out and return foodItems to particular method that calls it 
}; 

您需要了解Meteor如何讀取您的項目目錄。閱讀更多關於流星文檔中的structuring your application

1

你也可以創建此使用Template.registerHelper(name, function)全球幫手這將是這樣的:

Template.registerHelper('menuItems', function(eatingTime, sortCriteria) { 
    //do some checking of your arguments 
    eatingTime = eatingTime || '/* your default eating time */'; 
    sortCriteria = sortCriteria || {/* your default sort criteria */}; 
    check(eatingTime, String); 
    check(sortCriteria, Object); 

    //find and sort your items in one mongo query or you could do separate find and sort if you want 
    menuItems = EatingTimes.find({time: eatingTime}, sortCriteria); 

    return menuItems; 
}); 

這將是曬你的代碼的最流星方式。

,然後在你的模板,你可以把它作爲:

{{#each menuItems 'time args' 'sort arg'}} 
相關問題