Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a method to []?

First of all, I don't understand clearly what the type of this object (perhaps NativeArray ?). For me ember overrides the default javascript array with some mixins, by applying the NativeArray mixin to Array.prototype.

That beeing said, in my code, I want to do this kind of override by allowing:

["a", "b", "a"].count("a") // returns 2

I was trying to reopen the Enumerable Mixin (as for me it's the right place for this kind of function)

I'm sure that the reopen code is executed before using the count() method. But I encounter this error:

Object has no method count().

Reading the code it seems that I have to re-apply the mixin to the Array.prototype, but unfortunately, doing Ember.Enumerable.apply(Array.prototype) does nothing.

Update: After reading some articles, I begin to understand the prototype. I can add a function to an array with:

Array.prototype.newFunc = function () {
    console.log('bla');
}

But in my case, it's not satisfying as I want that for example, a MutableArray will be able to call newFun()

Perhaps the only way to do what I want is to make a PR to ember to include my count method to the Enumerable Mixin....

Any other suggestion is welcome :)

like image 689
sly7_7 Avatar asked Jan 16 '23 00:01

sly7_7


2 Answers

You're looking for reopen, it allows you to modify an existing class. Here is an example:

Ember.Enumerable.reopen({
    newFunc: function() {
        console.log('blah');
    }
});

WARNING: Calling reopen will not have an effect on objects which have already been instantiated. It will only effect objects created AFTER reopen has been called. In short, make sure you do reopen calls first.

like image 125
Wesley Workman Avatar answered Jan 29 '23 00:01

Wesley Workman


http://jsfiddle.net/kcjzw/249/

App = Ember.Application.create();

var NativeArray = Ember.Mixin.create(Ember.NativeArray, {
    count: function(ele) {
        var noOfEle = 20;
        //add your logic to count
        return noOfEle;
    }
});

NativeArray.apply(Array.prototype);
console.log(["a", "b", "a"].count("a")); //20

REF: Native Array in Emberjs does not support deep copy?

like image 21
sabithpocker Avatar answered Jan 28 '23 22:01

sabithpocker