HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Can I return an object on which a function is applied?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
canreturnfunctionappliedwhichobject

Problem

I'm wondering if it is possible or if it is correct to proceed in such a way:

var initiate_shop = function(shop_navigation, shop_container_id, items_per_page) {
    return $(shop_navigation).jPages({
        containerID     : shop_container_id,
        first           : false,
        previous        : false,
        next            : false,
        last            : false,
        midRange        : 15,
        perPage         : items_per_page,
        animation       : "fadeInUp",
        links           : "blank",
        keyBrowse       : true,
        scrollBrowse    : false,
        callback        : function(pages){
            current_page = pages.current;
            total_pages = pages.count;
        }
    });
};


If the above isn't correct what could be a better way to write it?

Solution

Looks good to me, if you always want those 3 params and never want to send anything else.

Otherwise, you could improve it by receiving the non-mandatory params in an options object:

"use strict";
var initiate_shop = function(container_id, options) {
    var default_settings = {
            containerID     : container_id,
            first           : false,
            perPage         : 5,
            '...'           : '...',
            callback        : function(pages){
                current_page = pages.current;
                total_pages = pages.count;
            }
        },
        settings = $.extend(default_settings, options);
    return $(shop_navigation).jPages(settings);
};
// ...
initiate_shop('outputCell', {
    perPage:     10,
    first:       true
});


Related (hows 3 ways to assign default values to parameters):

https://stackoverflow.com/a/3672142/148412

Code Snippets

"use strict";
var initiate_shop = function(container_id, options) {
    var default_settings = {
            containerID     : container_id,
            first           : false,
            perPage         : 5,
            '...'           : '...',
            callback        : function(pages){
                current_page = pages.current;
                total_pages = pages.count;
            }
        },
        settings = $.extend(default_settings, options);
    return $(shop_navigation).jPages(settings);
};
// ...
initiate_shop('outputCell', {
    perPage:     10,
    first:       true
});

Context

StackExchange Code Review Q#11623, answer score: 3

Revisions (0)

No revisions yet.