0

I have two buttons:

<button id="1">button 1</button>
<br>
<button id="2">button 2</button>

I want to make an alert message to appear only after the two buttons are clicked, this is part of a larger app for which I am using Backbone.js, so far I have this:

var test = {}; 

_.extend(test, Backbone.Events); //in order to use the backbone events feature

test.on("hello bye", function(){
    alert("works!");
});

$("#1").click(function() {
    test.trigger("hello");
});

$("#2").click(function() {
    test.trigger("bye");
}?);

This presents the message whenever one of the two buttons are clicked, but I need it to work only after the two buttons are clicked. Is there a way to achieve this using the Backbone.Events feature or perhaps using jQuery?

Fiddle: http://jsfiddle.net/ccgRN/

Thanks

rpabon
  • 1,191
  • 2
  • 16
  • 22

2 Answers2

2

Here's an idea using promises: http://jsfiddle.net/LFJGL/1/

Edit: fixed for older browsers:

var test = {};
var promises = [];
_.extend(test, Backbone.Events); //in order to use the backbone events feature

function GetAPromise() {
    var p = $.Deferred();
    promises.push(p);
    return p;
}

var events = "hello bye".split(" ");
_.each(events,function(event) {
    var p = GetAPromise();
    test.on(event, function() {
        p.resolveWith(event);
    });
});

$("#1").click(function() {
    test.trigger("hello");
});

$("#2").click(function() {
    test.trigger("bye");
});


$.when.apply($, promises).done(function() {
    alert('triggered');
    //might be nice to remove the event triggers here.
});​
JayC
  • 7,053
  • 2
  • 25
  • 41
1

A minimalist implementation would be to create a couple variables to keep track of what events have been fired.

var helloClicked = false;
var byeClicked = false;
var test = {};

_.extend(test, Backbone.Events);

test.on('hello bye'), function() {
  if (helloClicked && byeClicked) {
    alert('works!');
  }
});

$('#1').click(function() {
  helloClicked = true;
  test.trigger('hello');
});

$('#2').click(function() {
  byeClicked = true;
  test.trigger('bye');
});
Paul
  • 18,349
  • 7
  • 49
  • 56