Serenity UI Model

by jddevight

HTML

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://serenityui.com/libs/serenityui/js/serenityui-libs.min.js"></script>
<script src="https://serenityui.com/libs/serenityui/js/serenityui.min.js"></script>
<div id="results">
</div>

<div style="margin-top:20px;">
<span>Learn about this fiddle at:</span>
<a href="http://jsdev.wikidot.com/blog:7" target="_top">Serenity UI Class, Observable and Model</a>
</div>

JavaScript

// Define the Person Model.
var Person = serenity.Model.extend({
	firstName: null,
	lastName: null,
  
	constructor: function (values) {

		serenity.Model.call(this, values);
	},
  
	fullName: {
		get: function () {
			return serenity.format("{0} {1}", this.firstName, this.lastName);
		},
    set: function (value) {
    	var oldName = this.fullName;
    	var name = value.split(' ');
      this.set("firstName", name[0]);
      this.set("lastName", name[1]);
    }
	},
	
	greetings: function () {
		return serenity.format("Hello, my name is: {0}.", this.fullName);
	}
});

// Instantiate the person class.
var person = new Person({ firstName: "John", lastName: "Doe" });
person.bind("change", function (args) {
	$("#results").append(serenity.format("<div>Change Event: {0} changed from {1} to {2}</div>", 
  	args.property, args.before, args.value));
});
person.fullName = "Jack Smith";

// Call the greetings function.
$("#results").append(serenity.format("<div>{0}</div>", person.greetings()));

// Rollback the changes since the person instance was created.
person.rollback();
$("#results").append("<div>Rollback</div>");

// Call the greetings function.
$("#results").append(serenity.format("<div>{0}</div>", person.greetings()));