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 :)
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With