Last active
December 14, 2015 00:58
-
-
Save khepin/5002827 to your computer and use it in GitHub Desktop.
JS lazy evaluation and storing patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var SomeObject = { | |
views: { | |
firstPage: _.memoize(function(){ | |
return new FirstPageView(); | |
}) // Here all we have done is declare a function | |
// This function was never executed | |
}, | |
renderFirstPage: function() { | |
var v = this.views.firstPage(); // Either the function is executed | |
// Or it had already been called before | |
// and then the result (our view) is just | |
// returned from memory. | |
v.render(); | |
} | |
} | |
// Other way to do it with underscore: | |
function ViewStore() { | |
this.views = {}; | |
} | |
ViewStore.prototype.add = function(name, view) { | |
this.views[name] = view; | |
} | |
ViewStore.prototype.get = function(name) { | |
return _.result(this.views, name); | |
// _.result returns the value if it's a value | |
// or the return value if it's a function | |
} | |
var vs = new ViewStore; | |
vs.add('FirstPage', new FirstPageView()); // This is NOT lazy evaluation | |
// Here we have already created the view. | |
vs.add('SecondPage', function() { return new SecondPageView();}); | |
vs.add('ThirdPage', _.memoize(function() { return new ThirdPageView();})); | |
vs.get('FirstPage'); // => returns an object of type FirstPage | |
vs.get('FirstPage'); // => returns the same object object of type FirstPage | |
vs.get('SecondPage'); // => returns an object of type SecondPage | |
// This was lazily evaluated as we setup 'SecondPage' as a closure and never | |
// created the actual object before | |
vs.get('SecondPage'); // => returns a different object of type SecondPage | |
vs.get('SecondPage') === vs.get('SecondPage'); // => false | |
// It creates a new object every time. | |
vs.get('ThirdPage'); // => Returns an object of type ThirdPage, lazily evaluated too | |
// But this time: | |
vs.get('ThirdPage') === vs.get('ThirdPage'); // => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment