Calling custom baseline trigger not recognized?

I am learning Backbone.js for the first time, and am I having trouble trying to get a custom event from launch (or from a view from recognition when it starts)?

You can see my collection code here: https://github.com/Integralist/Backbone-Playground/blob/master/Assets/Scripts/App/main.js#L72-86 , which, when initialized, fires a custom collection:init event.

 var Contacts = Backbone.Collection.extend({ model: Contact, initialize: function(){ this.trigger('collection:init'); this.bind('add', this.model_added, this); }, model_added: function(){ console.log('A new model has been created so trigger an event for the View to update the <select> menu'); } }); 

But later in my view, where I am listening to this event, I cannot run the populate function: https://github.com/Integralist/Backbone-Playground/blob/master/Assets/Scripts/App/main.js#L90-107

 var ContactsView = Backbone.View.extend({ initialize: function(){ console.log(contacts.models, 'get initial model data and populate the select menu?'); }, events: { 'collection:init': 'populate', 'change select': 'displaySelected' }, populate: function(){ console.log('populate the <select> with initial Model data'); }, displaySelected: function (event) { console.log('get model data and display selected user', event); } }); 

Any ideas what I'm doing wrong?

+6
source share
1 answer

The event hash in the view is used to bind events from the DOM to your view, for example. events raised by elements in your visualized view. To listen to the events created by your collection, you will need to set them manually:

 var ContactsView = Backbone.View.extend({ initialize: function(){ contacts.on("collection:init",this.populate,this); } ... }); 

Note that you use the global contact variable, I would advise you to use the Backbone mechanisms and pass your collection to the constructor, as you do with el:

 var ContactsView = Backbone.View.extend({ initialize: function(){ console.log(this.collection.models); this.collection.on("collection:init",this.populate,this); } ... }); var contacts_view = new ContactsView({ el: $('#view-contacts'), collection:contacts }); 

As noted in the @mu comments in the comments, your event will not do anything, since you fire it in the collection initialization method, which is automatically called by the collection constructor, so before you can link something into the view. See this script to visualize the order of calls: http://jsfiddle.net/yRuCN/

Run it elsewhere, or if I read your intentions correctly, you (probably) want to use the built-in reset event:

 var ContactsView = Backbone.View.extend({ initialize: function(){ this.collection.on("reset",this.populate,this); } ... }); 

See http://jsfiddle.net/yRuCN/1/ for an example of potential uses.

+9
source

Source: https://habr.com/ru/post/921567/


All Articles