I have a backbone view that looks like this:
var myView = Backbone.view.extend({
events: {'click .myClass': 'myFunction'},
initialze: //initialize function,
render: //render function,
myFunction: function (e) {
//do something
}
});
I want to make myFunction
work only one time, then stop being called. I believe I could use the backbone once() method to achieve this but can't figure it out. Is this the best way and how do I structure it? Thanks!
js Event once() The event once method is just like event on method but it causes the bound callback to only fire once before being removed.
Backbone. js trigger Event is used to invoke or callback the function for the given event or a space-delimited list of events. The subsequent arguments will be passed along to the event callbacks in order to trigger it.
It represents a cached jQuery object for the view's element. A handy reference instead of re-wrapping the DOM element all the time.
The Backbone. js Views specify how your data looks like. They represent model's data to the users. They can be used with any JavaScript template library. They handle users input events, bind events and methods, render model and collection and interact with users.
Simply replace your current definition:
myFunction: function(){....}
by
myFunction: _.once(function(){....})
myFunction may be called several times, but it will be a noop after the first call.
View events are bound using delegateEvents
and that uses the delegation form of jQuery's on
. That means that the event to handler mapping is dynamic and can be manipulated by manipulating the DOM. For example, you could do this:
Backbone.View.extend({
events: {
'click .myClass.onlyOnce': 'doThings'
},
doThings: function(e) {
$(e.currentTarget).removeClass('onlyOnce');
//...
},
//...
});
and make sure that the .myClass
element also has an onlyOnce
class. Then, the first time you click on it, it will match .myClass.onlyOnce
and the click will get routed to doThings
; doThings
then proceeds to remove the onlyOnce
class and do whatever needs to be done. Subsequent clicks on .myClass
will be clicks on something that does not match .myClass.onlyOnce
so doThings
won't be called again.
This approach has the nice advantage of self documenting its behavior in events
.
Demo: http://jsfiddle.net/ambiguous/7KJgT/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With