M69
M69

Reputation: 506

YUI3 Objects and Namespacing with a Module

I'm having trouble understanding how to namespace and instantiate an object in YUI3. In the example below I'm creating a YUI3 module, loading it in the YUI.use method and trying to instantiate my object through namespacing. This doesn't work though, can someone point out why? I'm getting the error: "object is not a function" when trying to instantiate a new object.

test-module.js

YUI.add('test-module', function(Y){ 
var TestModule = {
    url: '',        

    /* Example function */
    doExample: function(){          
        console.log("doExample called");        
        }
}
// expose this back to the Y object
Y.namespace('SANDBOX.Test').TestModule = TestModule;
}, 1.0, {requires:['node']});

index.html

YUI({
    modules:{
        'test-module': {
            fullpath: 'js/test-module.js',
            requires: ['node']
        }
    }
}).use('test-module', function(Y){
    var testModule = new Y.SANDBOX.Test.TestModule(); //this throws the error
    testModule.doExample();
});

Upvotes: 1

Views: 330

Answers (1)

Lewis Diamond
Lewis Diamond

Reputation: 25001

The problem in your code (where you say it throws an exception) is that you're using new () on a plain object. This is not a constructor function.

Change the line

var testModule = new Y.SANDBOX.Test.TestModule(); //this throws the error

for

var testModule = Y.SANDBOX.Test.TestModule; //this doesn't throw the error

As for instantiating objects, it's no different than normal Javascript:

var f = function(){
    //This is the constructor
}
f.prototype.myfunction = function(){
    //this is a function
}

You also can use their base object to create your own custom objects.

var x = Y.Base.create('ClassIdentifier', |Base object to extend from|, [Extensions], {
    //content of the object, functions, etc
}, {
    ATTRS: {
        |attributes goes here|
    }
};
Y.namespace('mynamespcae').X = x;

Then you can do:

var xInstance = new Y.mynamespace.X();

See http://yuilibrary.com/yui/docs/base/ or more specifically for create: http://yuilibrary.com/yui/docs/base/#create

Upvotes: 3

Related Questions