EmberJS-Object-Model Classes and Instance



Description

You need to can instantiate a class by calling the create() method. You can also initialize the values for a class variables, by create() method. Ember.js uses init() method to automatically initialize instances of the class. It is simple to initialize the instance in Ember.js by using the setter and getter methods.

Syntax

var VarName = App.ClassName.create({
   VarName1:'values',
   VarName2:'values',
   ...
   VarName_n:'values'
});

Example

<!DOCTYPE html>
<html>
   <head>
      <title>Emberjs Classes and Instance</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">
         App = Ember.Application.create();

         App.Student = Ember.Object.extend({
            rollnum:'null',
            name: 'null',
         });

         App.StudentInfo = App.Student.extend({
            disp: function() {
               var roll = this.get('rollnum');
               var name = this.get('name');
               document.write("Student lists:<br>");
               document.write("Roll No: "+roll+" Name: "+name);
            }
         });
         var stud = App.StudentInfo.create({
            //initialize the values
            rollnum:'12',
            name: 'Manu',
         });

         //call the disp function
         stud.disp();
      </script>
   </body>
</html>

Output

Let's carry out the following steps to see how above code works −

  • Save above code in obj_mod_creat_init_inst.htm file

  • Open this HTML file in a browser.

Advertisements