- 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-Models Defining Attributes
Description
The DS.attr used to specify attributes for a model and it also takes an optional second parameter as hash −
Syntax
var attr = DS.attr;
DS.Model.extend({
VarName: attr(),
VarName: attr('DataType',{defaultValue: false}),
VarName: attr()
});
Example
<!DOCTYPE html>
<html>
<head>
<title>Emberjs Defining Attributes</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/x-handlebars" data-template-name="index">
<h2>Players Names:</h2>
{{#each person in controller}}
<p>{{person.id}}: {{person.name}}</p>
{{/each}}
</script>
<script type="text/javascript">
App = Ember.Application.create();
//The store cache of all records available in an application
App.Store = DS.Store.extend({
//adapter translating requested records into the appropriate calls
adapter: 'DS.FixtureAdapter'
});
App.ApplicationAdapter = DS.FixtureAdapter.extend();
//defining model
App.Person = DS.Model.extend({
name: DS.attr('string')
});
App.IndexRoute = Ember.Route.extend({
//index route
model: function() {
//return the person details
return this.store.find('person');
}
});
//attach fixtures(sample data) to the model's class
App.Person.FIXTURES = [
{id: 1, name: 'Virat'},
{id: 2, name: 'Raina'},
{id: 3, name: 'Dhoni'}
];
</script>
</body>
</html>
Output
Let's carry out the following steps to see how above code works −
Save above code in model_defn_attr.htm file
Open this HTML file in a browser.
Advertisements