tags:

views:

32

answers:

1

Let's say I had this class.

BucketList = new Class({

Implements: [Options, Events],

options: {
    items: [],
    onItemAddedOrDeleted: null
},

initialize: function(options, init) {
    this.setOptions(options);
    this.options.onItemAddedOrDeleted();
}
});

How can I get this to work?

new BucketList([], function() {
    alert(this.items.length);
});

Once instantiated, the new BucketList should alert the length of the array I passed into its constructor.

+2  A: 

A couple of issues here. One is that you're implementing Events, so the onItemAddedOrDeleted option becomes a Class instance event (see the docs for setOptions). As a result, you can't call onItemAddedOrDeleted as a normal function, as it becomes an event listener waiting for you to trigger an event of "itemAddedOrDeleted".

Two, your syntax for passing in the function as part of the options is slightly off, as you need to pass the custom init function as part of the options object. I've reworked your code slightly to use fireEvent instead of calling the function directly, but if you wanted to call it directly instead, you could just rename it to not use the event syntax (ie. start with 'on'). This works though:

BucketList = new Class({    
    Implements: [Options, Events],  
    options: {
        items: [],
        onItemAddedOrDeleted: null
    },  
    initialize: function(options) {
        this.setOptions(options);
        this.fireEvent('itemAddedOrDeleted');
    }
});

new BucketList({items:[],onItemAddedOrDeleted:function() {
    alert(this.options.items.length);
}});

Note that I surrounded the function being passed to the BucketList constructor as part of the options object.

You could do it without utilizing the Event syntax this way:

BucketList = new Class({    
    Implements: [Options, Events],  
    options: {
        items: [],
        itemAddedOrDeleted: null
    },  
    initialize: function(options) {
        this.setOptions(options);
        this.options.itemAddedOrDeleted();
    }
});    

var x = new BucketList({items:['x'],itemAddedOrDeleted:function() {
    alert(this.items.length);
}});
zombat