Serenity UI Obserable
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 class.
var Person = serenity.Observable.extend({
firstName: null,
lastName: null,
events: ["nameChange"],
constructor: function (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
serenity.Observable.call(this);
},
fullName: {
get: function () {
return serenity.format("{0} {1}", this.firstName, this.lastName);
},
set: function (value) {
var oldName = this.fullName;
var name = value.split(' ');
this.firstName = name[0];
this.lastName = name[1];
this.trigger("nameChange", { oldName: oldName, newName: this.fullName });
}
},
greetings: function () {
return serenity.format("Hello, my name is: {0}.", this.fullName);
}
});
// Instantiate the person class.
var person = new Person("John", "Doe");
person.bind("nameChange", function (args) {
console.log("nameChange", args);
$("#results").append(serenity.format("<div>Name changed from {0} to {1}</div>", args.oldName, args.newName));
});
person.fullName = "Jack Smith";
// Call the greetings function.
$("#results").append(serenity.format("<div>{0}</div>", person.greetings()));