最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Backbone.js - Custom collection events - Stack Overflow

programmeradmin1浏览0评论

I'm trying to implement custom collection events for view binding.

In my view I want to do something like:

this.collection.on('available', this.available);

And somehow trigger this in method within my collection.

So say I have a method in my collection which sets a particular models attribute (available), how could I then trigger all views that are bound to this method?

Is this possible, and able to pass the model in question to the view for updating.

Thanks for any help in advance, much appreciated :)

I'm trying to implement custom collection events for view binding.

In my view I want to do something like:

this.collection.on('available', this.available);

And somehow trigger this in method within my collection.

So say I have a method in my collection which sets a particular models attribute (available), how could I then trigger all views that are bound to this method?

Is this possible, and able to pass the model in question to the view for updating.

Thanks for any help in advance, much appreciated :)

Share Improve this question asked Sep 19, 2012 at 10:23 jahilldevjahilldev 3,8127 gold badges37 silver badges53 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

It's very simple to add new events to Backbone. You just need to call the trigger method on the object that you want to trigger the event on.

For example, assuming you're in a method of the collection, and have a model (called model):

this.trigger('available', model);

The code to bind to the available event would just be as you described in your question.

EDIT: These days Backbone provides a listenTo method that you should usually use when binding to collection events from your views. Views will automatically unbind from this event when their remove function is called, which stops old views from continuing to receive collection events after they have been removed. From your view, this can be used like this:

this.listenTo(this.collection, 'available', this. available);
发布评论

评论列表(0)

  1. 暂无评论