chris
chris

Reputation: 36937

Extending upon a jQuery plugin, without necessarily touching the original plugin code

Right now I am making use of a great cookie handler I found https://github.com/carhartl/jquery-cookie for jquery. Only problem is, it will only set cookies by days. I would like to be able to bypass that and set them by seconds/hours in some cases, or maybe even to a specific time.

Looking at the plugin I know where I cam make the alterations to it specifically. But I am wondering is there a means of extending the plugin with my own custom code somehow so when I call the plugin like normal I can use parameters I've set. The whole idea is to avoid hacking into the initial script so if the author does release a new version in time I can update it accordingly and not lose any changes I may forget about in the upgrade process.

In the current plugin line 44-47 there is

if (typeof options.expires === 'number') {
                var days = options.expires, t = options.expires = new Date();
                t.setDate(t.getDate() + days);
            }

which I know I can hack directly into that and do as I want. But the idea again is to do it through some external means using the same script overall

Upvotes: 4

Views: 96

Answers (3)

fardjad
fardjad

Reputation: 20394

As suggested by others, I think the plugin already supports the functionality you want to add. But I'm going to answer your question > I am wondering is there a means of extending the plugin with my own custom code:

The plugin sets $.cookie to a function with three arguments (function (key, value, options)). You can extend it this way:

// in a js file after including `jquery.cookies.js`
(function () {
    var cookie = $.cookie;
    $.cookie = function (key, value, options) {
        // TODO: add your code here

        $.cookie = cookie;
        var out = $.cookie(key, value, options);
        $.cookie = this;
        return out;
    }
}());

Upvotes: 1

Francis Kim
Francis Kim

Reputation: 4285

You can divide the number of seconds you want by 86400. So for 30 seconds use:

$.cookie('the_cookie', 'the_value', { expires: 30/86400, path: '/' });

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

I don't think that assumption is correct.

you can use

$.cookie('my-key', 'my-valye', {
    expires: new Date()
})

Or

var expires = new Date();
expires.setHours(expires.getHours() + 1);
$.cookie('my-key', 'my-valye', {
    expires: expires 
})

Upvotes: 0

Related Questions