Skip to content

Instantly share code, notes, and snippets.

@sleepynate
Created February 1, 2012 06:03
Show Gist options
  • Select an option

  • Save sleepynate/1715403 to your computer and use it in GitHub Desktop.

Select an option

Save sleepynate/1715403 to your computer and use it in GitHub Desktop.
backbone events wat
it("derps when using a space in an event name", function() {
var callback = jasmine.createSpy('-Custom Event Callback-');
obj.bind('all', callback);
obj.trigger("foo bar");
expect(callback.callCount).toBe(1);
expect(callback.mostRecentCall.args[0]).toBe('foo bar');
});
@davemo

davemo commented Feb 1, 2012

Copy link
Copy Markdown

Does this throw a syntax error or just have output different than what you expected? I was thinking for the example given on the backbone 0.9 changelog you could bind 2 model fields to change like they do, then do a model.set with those values and expect the callback was called.

it("triggers a callback based on model attribute changes", function() {
  var person = new (Backbone.Model.extend({
           name: "Dave",
           age: 30,
           location: "Saskatoon"
       }))(),
       callback = jasmine.createSpy("-stuff-");

       person.bind("change:name change:location", callback);

       person.set({ name: "Nate", location: "Ann Arbor" });

       expect(callback.count).toBe(2); // etc...
});

@sleepynate

sleepynate commented Feb 1, 2012 via email

Copy link
Copy Markdown
Author

@davemo

davemo commented Feb 1, 2012

Copy link
Copy Markdown

I think it makes sense, the callback would be fired twice given 2 events are being triggered, I think the test just needs to be more explicit about that.

@sleepynate

Copy link
Copy Markdown
Author

EXCEPT that on line 5, you used to be able to name a single event "foo bar"

@davemo

davemo commented Feb 1, 2012

Copy link
Copy Markdown

Ah, so binding works with space-separated events but triggering is still a singular operation. That makes sense because arguments from .trigger are passed along to the function that was bound. Triggering two events at once doesn't seem like it would be something that would be frequently done and even if you wanted to you would have no way to determine which arguments were passed to the callback. (By convention backbone passes the model instance AND the changed attribute[singular] to the callback).

@davemo

davemo commented Feb 1, 2012

Copy link
Copy Markdown

In the case of

    person.bind("change:name change:location", callback);

the callback will fire two times and the arguments will contain the model and changed value of each field
ie:
callback(model, name);
callback(model, location);

@sleepynate

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment