-
-
Save mxriverlynn/1604401 to your computer and use it in GitHub Desktop.
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"); | |
}); | |
}); | |
}); |
that's the rough idea. it's something that one of my current projects needs, and I'm tired of hard coding a ton of this.bind("change:...")
statements in to model initialize
methods for this purpose.
gotcha. I used this (albeit this is an old) version for a while when I was first spiking:
https://gist.github.com/1355346
Useful concept across the board, IMO
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.
... 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. :)
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?
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.
Is this a backbone version of ko's dependent observable concept?