Reputation: 2279
I'm trying to extend a Object and add some custom instance methods to it. How do I access data in attributes?
const Media = Parse.Object.extend('Media', {
getUrl: function getUrl() {
// HOW DO I ACCESS ATTRIBUTES HERE?
},
});
const url = new Media({
url: 'url here',
}).getUrl()
I basically expected attribute values to live either in this or in this.get('url')
So how do I get access to attributes inside of instance method?
Thanks
Upvotes: 0
Views: 105
Reputation: 2279
It turned out that I tried to execute getUrl()
method on a nested object, however I didn't included this object in query.
Upvotes: 0
Reputation: 6608
The problem with your code is that you're trying to use a constructor which doesn't initialize your instance.
const url = new Media({
url: 'url here',
});
Here you're passing a state object
with url
property to Media
constructor but you are not actually capturing that object to initialize your instance, so the object is simply ignored. Hence there's no property by the name url
on your instance and this.url
will be undefined
.
As documented here, Parse.Object.extend()
will return a subclass of Parse.Object
for the given class name. The second argument to extend()
is an object containing instance properties/methods which are available to all the instances. Once you defined the class, you can create a new instance using the new
keyword. If you have several parameters to initialize while creating the instance, you can make use of the initialize
method like below.
const Media = Parse.Object.extend('Media', {
initialize : function(state){
this.url = state.url;
this.type = state.type;
},
getUrl: function getUrl() {
return this.url;
},
getType : function(){
return this.type;
}
});
Then create a instance by calling the constructor new keyword and passing the state object like below
const url = new Media({
'url' : 'myURL',
'type' : 'video'
});
url.getType(); // returns 'video'
url.getUrl(); // returns 'myURL'
Upvotes: 1