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

gotcha. I used this (albeit this is an old) version for a while when I was first spiking:
https://gist.github.com/1355346

@jmarnold
Copy link

Useful concept across the board, IMO

@mxriverlynn
Copy link
Author

heh - that's about 99% the same code I have in mine. :)

I wanted to make this a little more "declarative" like other backbone constructs, instead of stuffing it in to an initializer. although what you've written is significantly more simple, and gets around several of the problems that led me to my current solution.

@mxriverlynn
Copy link
Author

... of course, my version of this idea doesn't come close to a "declarative" model yet. it's single use, essentially, because it's a constructor function. still needs work. might just steel yours and use that. :)

@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