javascript - Ember.js: When is a model accessible to the controller? -
in ember, when model accessible controller?
below simple ember application static model , controller attempts access model on init
. you'll notice on init
model title
attribute undefined
. however, settimeout illustrates model
later accessible.
i under impression ember wouldn't initiate controller until model ready. correct? ember documentation (http://emberjs.com/guides/routing/specifying-a-routes-model/) indicates models, when loaded asynchronously available when controller instantiated.
http://jsfiddle.net/vu263uwq/1/
app = ember.application.create({}); app.indexroute = ember.route.extend({ model: function() { homecoming posts[0]; } }); app.indexcontroller = ember.objectcontroller.extend({ alerttitle: function() { var = this; jquery(".output").append("1. "+this.get("title")+"<br />"); //returns "undefined" settimeout(function() { jquery(".output").append("2. "+that.get("title")); //returns right title }, 1000); }.on("init") }); var posts = [ { id: 1, title: "first title", body: "cras mattis consectetur purus sit down amet fermentum. fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit down amet risus. nullam quis risus eget urna mollis ornare vel european union leo. cras justo odio, dapibus ac facilisis in, egestas eget quam." },{ id: 2, title: "second title", body: "maecenas faucibus mollis interdum. vestibulum id ligula porta felis euismod semper. cras justo odio, dapibus ac facilisis in, egestas eget quam. fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit down amet risus. aenean european union leo quam. pellentesque ornare sem lacinia quam venenatis vestibulum." } ];
your impression wrong. setupcontroller hook set properties on controller, including model. actually, setupcontroller
default set model on controller. that's why if override hook , still need model
set, must explicitly set model or create phone call this._super(controller, model)
.
notice signature setupcontroller:
setupcontroller: function(controller, model)
in order work, controller must instantiated point ember sets model. init fired during instantiation of controller. phone call init
happens before model
set`
as asynchronous fetching of models, if model hook returns promise, ember block until fulfilled promise can passed setupcontroller
function model assigned promise's fulfillment , not promise itself. lets avoid calls like:
setupcontroller: function(controller, model){ var self = this; makeasynccallreturningpromise().then(function(result){ self._super(controller, result); } }
which accomplish same thing
javascript ember.js
No comments:
Post a Comment