- Getting backbone.js to run a function after constructing a Collection?
- var Everything = Backbone.Model.extend({
- url: "/static/data/mydata.json",
- parse: function(data)
- {
- this.set("things", new Things(data.things, {controller: this}));
- }
- });
- var Thing = Backbone.Model.extend({
- });
- var Things = Backbone.Collection.extend({
- model: Thing,
- initialize: function(data, options)
- {
- // HERE I want access to this.models.
- // Unfortunately it has not yet been populated.
- console.log("initialize");
- console.log(this.models);
- // result: []
- // And this event never gets triggered either!
- this.on("all", function(eventType)
- {
- console.log("Some kind of event happend!", eventType);
- });
- }
- });
- var everything = new Everything();
- everything.fetch();
- // Some manual poking to prove that the demo code above works:
- // Run after everything has happened, to prove collection does get created with data
- setTimeout(function(){console.log("outside data", everything.get("things").models);}, 1000);
- // This has the expected result, prints a load of models.
- // Prove that the event hander works.
- setTimeout(function(){console.log("outside trigger", everything.get("things").trigger("change"));}, 1000);
- // This triggers the event callback.
- initialize: function(data, options) {
- _.defer(_.bind(this.doSomething, this));
- },
- doSomething: function() {
- // now the models are going to be available
- }
- var Everything = Backbone.Model.extend({
- initialize: function() {
- this.things = new Things();
- this.resetThings();
- this.on("change:things", this.resetThings, this);
- },
- resetThings: function() {
- // resets the collection with the current data
- this.things.reset(this.get("things"));
- }
- });
- var Thing = Backbone.Model.extend({});
- var Things = Backbone.Collection.extend({
- model: Thing,
- initialize: function(data, options) {
- this.on("reset", this.initializeThings, this);
- },
- initializeThings: function() {
- console.log("initializeThings");
- console.log(this.pluck("id"))
- }
- });
- var everything = new Everything({
- things: []
- });
- everything.set({
- every: "loaded",
- things: [{"id": "thing1"},{"id": "thing2"}]
- });