- EmberJS - Home
- EmberJS - Overview
- EmberJS - Installation
- EmberJS - Core Concepts
- Creating and Running Application
- EmberJS - Object Model
- EmberJS - Router
- EmberJS - Templates
- EmberJS - Components
- EmberJS - Models
- EmberJS - Managing Dependencies
- EmberJS - Application Concerns
- EmberJS - Configuring Ember.js
- EmberJS - Ember Inspector
EmberJS - Reopening Classes and Instances
Reopening Classes and Instances
This is nothing but updating the class implementation without redefining it. It is necessary only when you don't want to extend the built in classes, but update their implementation. This is possible by using following methods −
reopen() − This method usually adds the properties and methods to instances.
reopenClass() − method adds the properties and methods to the classes.
var Person = Ember.Object.extend({
firstName: null,
lastName: null
});
Person.reopen({
middleName: 'Smith'
});
var Person = Ember.Object.extend({
firstName: null,
lastName: null
});
Person.reopenClass({
createMan: function() {
return Person.create({isMan: true})
}
});
The above code describes how to reopen the class Person to add the variable name middleName to an instance and reopenClass to add the createMan function for Person class.
Example
<!DOCTYPE html>
<html>
<head>
<title>Emberjs Reopening Classes and Instances</title>
<!-- CDN's-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.1/handlebars.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.10.0/ember.min.js"></script>
<script src="https://builds.emberjs.com/tags/v1.10.0-beta.3/ember-template-compiler.js"></script>
<script src="https://builds.emberjs.com/release/ember.debug.js"></script>
<script src="https://builds.emberjs.com/beta/ember-data.js"></script>
</head>
<body>
<script type="text/javascript">
//reopen() method for instances
var Person = Ember.Object.extend({
firstName: null,
lastName: null,
});
//adding new variable to the Person class
Person.reopen({
middleName: 'Smith',
});
document.write('Middle Name: '+Person.create().get('middleName'));
//reopenClass() method for classes
var Person = Ember.Object.extend({
firstName: null,
lastName: null,
});
Person.reopenClass({
//creating new method for class Person
createMan: function() {
return Person.create({isMan: true})
}
});
document.write('isMan: '+Person.createMan().get('isMan'));
</script>
</body>
</html>
Output
Let's carry out the following steps to see how above code works −
Save above code in reopncls_inst.htm file
Open this HTML file in a browser.
Advertisements