Class objects MooTools and 'this'

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 make this work?

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

After creating the instance, I new BucketListmust warn the length of the array that I passed to its constructor.

+3
source share
1 answer

A few questions are here. First, you implement Events, so the parameter onItemAddedOrDeletedbecomes an instance of the class (see Docs for setOptions ). As a result, you cannot call it onItemAddedOrDeletedlike a regular function, since it will become an event listener, waiting for the event "itemAddedOrDeleted" to be called.

, , init options. , fireEvent , , , (.. 'on'). , :

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);
}});

, , BucketList, options.

Event :

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);
}});
+4

Source: https://habr.com/ru/post/1730149/


All Articles