2

I am having a bit of trouble creating an instance of useful things from another JS file, I would like to change the properties of the instance and use the methods. Or whatever you suggest if this is not possible. This extends and this construct are confusing me.

(function($) {

$.extend({
    usefulThings: new function() {
        this.defaults = {
            prop_path:'/la/lala',
            //OTHER STUFF
        };
        this.construct = function(options) {
            return this.each(function() {
                var setting;
                this.settings = {};
                settings = $.extend(this.settings, $.usefulThings.defaults, options);
                $this = $(this);

                //OTHER STUFF
                $.data(this, "usefulThings",settings);
                // FIRST METHOD CALL
                //OTHER STUFF
            });
        };
        //SOME METHODS
    }
});
$.fn.extend({
    usefulThings: $.usefulThings.construct
}); 
})(jQuery);      

I have seen usefulThings called from script blocks like so:

$("#myDivName").usefulThings({
  prop_path: '/la/lala' //these seems to get overwritten in the above
});

1 Answers1

0

First, have a look at MDN's introduction to the this keyword. And in the jQuery docs for .each.

Next, check out how does jquery chaining work? to understand the construct method.

Then, you should notice that the use of the new keyword is absolutely inappropriate in this case. The expression should be replaced by a simple object literal:

{
    defaults: {
        prop_path:'/la/lala',
        // …
    },
    construct: function(options) {
        …
    },
    //SOME METHODS
}

Now, the jQuery.extend. The relevant sentence from the docs is

If only one argument is supplied to $.extend(), this means the target argument was omitted. In this case, the jQuery object itself is assumed to be the target. By doing this, you can add new functions to the jQuery namespace. This can be useful for plugin authors wishing to add new methods to JQuery.

And it's the same for $.fn.extend (which actually is === $.extend), it extends the jQuery.fn object which is a shortcut for jQuery's prototype object.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I looked into all the stuff you wrote and it was pretty informative. I learned a few things. Ultimately, my problem was the file containing usefulThings hadn't loaded yet when I tried to call it. I wrapped it in window.onload = function() {$("#myDivName").usefulThings({prop_path: '/la/lala'});} and it worked. I feel like someone just told me to clear my cache. feelin' real rookie right now. – Corteo Tazu Feb 11 '13 at 20:44