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.
Pregunta
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!
Solución
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.
Otros consejos
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
.
You could add an attribute to the element the first time, and then check if the element has the attribute:
var myView = Backbone.view.extend({
events: {'click .myClass': 'myFunction'},
initialze: //initialize function,
render: //render function,
myFunction: function (e) {
if(e.target.getAttribute("data-fired")) return;
e.target.setAttribute("data-fired", true);
// Do your stuff
}
});
You could add a class to the element to validate your condition.
var myView = Backbone.view.extend({
events: {
'click .myClass': 'myFunction'
},
initialze: //initialize function,
render: //render function,
myFunction: function (e) {
if (e.target.className.search(/triggered/) !== -1) return; // event already triggered once
e.target.className += "triggered";
//do something when its triggered first time
}
});