Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created January 13, 2012 03:15
Show Gist options
  • Save mxriverlynn/1604401 to your computer and use it in GitHub Desktop.
Save mxriverlynn/1604401 to your computer and use it in GitHub Desktop.
backbone viewmodels
describe("backbone viewmodel", function(){
describe("when an underlying model attribute is changed", function(){
var model, vm, changeEvent;
beforeEach(function(){
changeEvent = false;
model = new Backbone.Model();
// --------------------------
// here's the important stuff
// --------------------------
vm = new Backbone.ViewModel(model, function(vm){
vm.observable("modifiedFoo", function(){
var foo = this.model.get("foo");
return foo + " was modified";
});
});
vm.bind("change:modifiedFoo", function(val){
changeEvent = val;
});
// --------------------------
model.set({foo: "bar"});
});
it("should update the view model attribute", function(){
expect(vm.get("modifiedFoo")).toBe("bar was modified");
});
it("should trigger a change event for the changed attribute", function(){
expect(changeEvent).toBe("bar was modified");
});
});
});
@jmarnold
Copy link

I'm not sure I get where you're going with the "declarative" model. Do you have an example of the syntax you'd wanna use?

@mxriverlynn
Copy link
Author

well the syntax that i would want to use isn't valid in javascript :P or at least, the way context works in javascript, it ends up not being possible.

something like this:

Backbone.Model.extend({
  someAttr: Backbone.ViewModel.observer(function(){
    return this.get("foo") + " " + this.get("bar");
  });
});

the problem is that I won't know what attribute this is being assigned to. There's no way for me to know that the result should be assigned to "someAttr". There's also no way for me to attach the result of the call to observer to the extended instance of Backbone.Model... it will always end up attached to the ViewModel object because the context of the call to observer will be set to ViewModel.

... blargh.

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