Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a backbone view event only once?

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!

like image 835
YPCrumble Avatar asked Feb 19 '14 03:02

YPCrumble


People also ask

Which function has to be used when you want to trigger the event only once before being removed?

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.

How do you trigger an event in the backbone?

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.

What is $El in backbone?

It represents a cached jQuery object for the view's element. A handy reference instead of re-wrapping the DOM element all the time.

What is a backbone view?

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.


2 Answers

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.

like image 123
Greg Avatar answered Oct 03 '22 05:10

Greg


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/

like image 43
mu is too short Avatar answered Oct 03 '22 06:10

mu is too short