public
Created

  • Download Gist
asynchrony.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
/**
* This gist illustrates how you can use placeholder objects to
* abstract the mechanism by which information becomes available
* from the need to update the DOM when it does.
*
* Note: the current release of SproutCore uses .property(), not
* .dependsOn() as in this example.
*/
 
// The Person object exposes firstName, lastName and fullName and
// isLoaded to other objects. It is may asynchronously populate
// those properties but listeners don't have to know exactly how
// that population will occur
App.Person = SC.Object.extend({
// firstName delegates to the data hash
firstNameBinding: 'data.firstName',
 
// lastName delegates to the data hash
lastNameBinding: 'data.lastName',
 
// fullName just uses the object's firstName and lastName;
// it is isolated from the asynchrony of the initial load
fullName: function() {
return this.get('firstName') + ' ' + this.get('lastName')
}.dependsOn('firstName', 'lastName'),
 
// returns true if the firstName and lastName are present.
// this computed property is isolated from how exactly
// those properties are populated. If they are populated
// initially, isLoaded will always be true.
isLoaded: function() {
return this.get('firstName') && this.get('lastName');
}.dependsOn('firstName', 'lastName'),
 
// load in the person from Ajax and populate the data
// property when done.
load: function(id) {
var self = this;
 
$.getJSON("/people/" + id, function(json) {
this.set('data', json.person);
});
return this;
}
});
 
// A PersonView represents a Person in the DOM. It is totally isolated
// from the way that the Person's properties are loaded.
App.PersonView = SC.View.extend({
render: function(buffer) {
// Is the person ready to be represented in the DOM. If not, just
// insert an empty <div> wrapper.
if (this.getPath('person.isLoaded')) {
buffer.push("<p>" + this.getPath('person.fullName') + "</p>");
}
},
 
// when the Person object becomes loaded, or its full name changed,
// update the view's representation in the DOM.
personChanged: function() {
if (this.getPath('person.isLoaded') { this.rerender(); }
}.observes('person.isLoaded', 'person.fullName')
});
 
var person = App.Person.create().load(12);
var personView = App.PersonView.create({ person: person });
personView.appendTo('#some-node');

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.